/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.approval.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.icinfo.cloud.common.core.config.CfRedisRepository;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.constant.ExecuteConstant;
import com.icinfo.cloud.provider.common.enums.ApiVisitDataSourceEnum;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.OpinionType;
import com.icinfo.cloud.provider.common.enums.TerritoryCodeEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.DateUtil;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.common.utils.SpringContextUtil;
import com.icinfo.cloud.provider.common.zzd.DingDingUtil;
import com.icinfo.cloud.provider.peripheralinterface.datareport.service.IDataReportService;
import com.icinfo.cloud.provider.peripheralinterface.lawenforce.dto.CaseBaseInfoStatusUpdateDto;
import com.icinfo.cloud.provider.peripheralinterface.lawenforce.service.ILawenforceBusinessService;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.punish.actscode.dto.ActsCodeDto;
import com.icinfo.cloud.provider.punish.actscode.service.ICaseActsCodeInfoService;
import com.icinfo.cloud.provider.punish.api.dto.CaseBaseInfoResponse;
import com.icinfo.cloud.provider.punish.api.service.ICaseTransferApiService;
import com.icinfo.cloud.provider.punish.approval.constant.AuditStatusConstant;
import com.icinfo.cloud.provider.punish.approval.dto.*;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalCompleteRecordMapper;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalFlowRelationMapper;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalWaitRecordMapper;
import com.icinfo.cloud.provider.punish.approval.model.CaseApprovalCompleteRecord;
import com.icinfo.cloud.provider.punish.approval.model.CaseApprovalFlowRelation;
import com.icinfo.cloud.provider.punish.approval.model.CaseApprovalWaitRecord;
import com.icinfo.cloud.provider.punish.approval.service.ICaseApprovalWaitRecordService;
import com.icinfo.cloud.provider.punish.approval.vo.*;
import com.icinfo.cloud.provider.punish.common.caseregister.service.IRegisterCommonService;
import com.icinfo.cloud.provider.punish.common.datareport.dto.CollectReportDataDto;
import com.icinfo.cloud.provider.punish.common.datareport.enums.CaseChangeOperationTypeEnum;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataChangeReportRecordService;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.RebuildDocumentDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.common.systemmessage.dto.SystemMessageInsertDto;
import com.icinfo.cloud.provider.punish.common.systemmessage.service.ICaseSystemMessageService;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiParamDocumentInfoMapper;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigCaseApprovalCenterLineMapper;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigCaseApprovalCenterMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.ConfigCaseApprovalCenterLine;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigDefaultApprovalPersonService;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.config.vo.ConfigCaseApprovalCenterVo;
import com.icinfo.cloud.provider.punish.coordination.lawjoin.dto.EditCaseStatusDto;
import com.icinfo.cloud.provider.punish.coordination.lawjoin.service.ILawJoinService;
import com.icinfo.cloud.provider.punish.csource.manage.dto.FlowCommonDto;
import com.icinfo.cloud.provider.punish.csource.manage.enums.CaseSourceStatusEnum;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceFlowRecordMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourcePartyInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceRegisterMainInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceFlowRecord;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourcePartyInfo;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceRegisterMainInfo;
import com.icinfo.cloud.provider.punish.csource.manage.service.ICaseSourceFlowRecordService;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteDataRequestDto;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteFlowCommonDto;
import com.icinfo.cloud.provider.punish.execute.enums.ExecuteStateEnum;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecuteDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecuteMainInfoMapper;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecutePartyInfoMapper;
import com.icinfo.cloud.provider.punish.execute.model.ExecuteDocumentRecord;
import com.icinfo.cloud.provider.punish.execute.model.ExecuteHandlePersonRecord;
import com.icinfo.cloud.provider.punish.execute.model.ExecuteMainInfo;
import com.icinfo.cloud.provider.punish.execute.model.ExecutePartyInfo;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteDocCommonOperateService;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteFlowRecordService;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteHandlePersonRecordService;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.PunishMsgParams;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStatusEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseHandlePersonRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.cloud.provider.punish.ucase.caseregister.service.ICaseRegisterService;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.enums.CaseStatusChangeEffectEnum;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.enums.CaseStatusChangeTypeEnum;
import com.icinfo.cloud.provider.punish.usersign.mapper.MemberUserSignMapper;
import com.icinfo.cloud.workflow.common.annotation.WorkFlowRollAnnotation;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.cloud.xzcf.provider.member.userinfo.model.MemberUserInfo;
import com.icinfo.cloud.xzcf.provider.member.zfpeople.dto.ZfPeopleBaseInfoVO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.icinfo.framework.tools.utils.DateUtils;
import com.icinfo.framework.tools.utils.MapUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述: 案件文书待审批记录表 case_approval_wait_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年02月15日
 */
@Service
@Transactional(rollbackFor = {Error.class, Exception.class})
@Slf4j
public class CaseApprovalWaitRecordServiceImpl extends MyBatisServiceSupport implements ICaseApprovalWaitRecordService {
    @Resource
    private CaseApprovalWaitRecordMapper caseApprovalWaitRecordMapper;

    @Resource
    private CaseApprovalCompleteRecordMapper caseApprovalCompleteRecordMapper;

    @Resource
    private CaseApprovalFlowRelationMapper caseDocuApprovalFolwRelationMapper;

    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;

    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;

    @Resource
    private ConfigBusiParamDocumentInfoMapper configBusiParamDocumentInfoMapper;

    @Resource
    private IStageDocCommonOperateService stageDocCommonOperateService;

    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;

    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;

    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;

    @Resource
    private IRegisterCommonService iRegisterCommonService;

    @Value("${member.api.getCaseUserList}")
    private String getCaseUserList;
    @Value("${member.url}")
    private String memberUrl;
    @Value("${ding.sendUrl}")
    private String dingSendUrl;
    @Value("${ding.dingIdUrl}")
    private String dingIdUrl;
    @Value("${taskCenter.url}")
    private String taskCenterUrl;
    @Value("${taskCenter.api.saveEntMessage}")
    private String saveEntMessage;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private IExecuteMainInfoService executeMainInfoService;

    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private ICaseSourceFlowRecordService caseSourceFlowRecordService;
    @Resource
    private IExecuteFlowRecordService executeFlowRecordService;

    @Resource
    private CaseSourceFlowRecordMapper caseSourceFlowRecordMapper;
    @Resource
    private CaseSourceRegisterMainInfoMapper caseSourceRegisterMainInfoMapper;
    @Resource
    private ExecuteDocumentRecordMapper executeDocumentRecordMapper;
    @Resource
    private IExecuteHandlePersonRecordService executeHandlePersonRecordService;
    @Resource
    private IExecuteDocCommonOperateService executeDocCommonOperateService;


    @Resource
    private MemberUserSignMapper memberUserSignMapper;
    @Resource
    private ICaseActsCodeInfoService caseActsCodeInfoService;
    @Resource
    private CaseApprovalFlowRelationMapper caseApprovalFlowRelationMapper;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;


    private static final String LOCKPREFIX = "APPROVAL:";

    /**
     * 联合法制审核（角色）
     */
    @Value("${approval.center.roleId}")
    private String caseApprovalCenterRole;

    @Resource
    private ICaseMainEvidenceService caseMainEvidenceService;

    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;

    //    @Resource
//    private RedissonClient redissonClient;
    @Resource
    private ConfigCaseApprovalCenterMapper configCaseApprovalCenterMapper;
    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Resource
    private ConfigCaseApprovalCenterLineMapper configCaseApprovalCenterLineMapper;

    @Resource
    private ICaseHandlePersonRecordService caseHandlePersonRecordService;
    @Resource
    private ICaseMainInfoStatusChangeRecordService caseMainInfoStatusChangeRecordService;
    @Resource
    private CaseSourcePartyInfoMapper caseSourcePartyInfoMapper;
    @Resource
    private ICaseRegisterService caseRegisterService;
    @Resource
    private ExecuteMainInfoMapper executeMainInfoMapper;
    @Resource
    private ExecutePartyInfoMapper executePartyInfoMapper;
    @Resource
    private ICaseDistributionRecordService caseDistributionRecordService;
    @Resource
    private IConfigDefaultApprovalPersonService configDefaultApprovalPersonService;
    @Resource
    private ICaseSystemMessageService caseSystemMessageService;
    @Resource
    private CaseMainDetailAuxiliaryInfoMapper mainDetailAuxiliaryInfoMapper;
    @Resource
    private ILawenforceBusinessService lawenforceBusinessService;
    @Resource
    private ILawJoinService lawJoinService;
    @Resource
    private ICaseTransferApiService caseTransferApiService;
    @Resource
    private ICaseDataChangeReportRecordService caseDataChangeReportRecordService;
    @Resource
    private CfRedisRepository cfRedisRepository;
    @Resource
    private ICaseDocumentModifyRecordService caseDocumentModifyRecordService;
    @Resource
    private IDataReportService dataReportService;


    @Override
    public List<AuditInfoListVo> getWaitList(AuditQueryPageDto auditQueryPageDto) {
        PageHelper.startPage(auditQueryPageDto.getPageNum(), auditQueryPageDto.getLength());
        if (auditQueryPageDto.getLength() > 200) {
            throw new BusinessException("每页条数不能超过200");
        }
        //获取当前用户
        UserDTO userDTO = UserUtil.getUserInfo();
        auditQueryPageDto.setUserId(userDTO.getUserId().toString());

        //是否联合法制审核为空默认为0
        if (StringUtils.isBlank(auditQueryPageDto.getIsApprovalCenter())) {
            auditQueryPageDto.setIsApprovalCenter("0");
        }
        List<AuditInfoListVo> list = null;
        // 联合法制审核 查询
        String one = "1";
        if (StringUtils.isNotBlank(auditQueryPageDto.getIsApprovalCenter()) && one.equals(auditQueryPageDto.getIsApprovalCenter())) {
            PageHelper.startPage(auditQueryPageDto.getPageNum(), auditQueryPageDto.getLength());
            list = caseApprovalWaitRecordMapper.getWaitListCenter(auditQueryPageDto);
        } else {
            PageHelper.startPage(auditQueryPageDto.getPageNum(), auditQueryPageDto.getLength());
            list = caseApprovalWaitRecordMapper.getWaitList(auditQueryPageDto);
        }
        //处理时效
        int dfds = 0;
        Example example = new Example(CaseReasonMainRecord.class);
        for (AuditInfoListVo vo : list) {
            // timeColor 单独查询处理
//            RED("red","分红（当前日期-截止日期<0)",-1),
//            ORANGE("orange","橙(当前日期-截止日期<=3)",3),
//            YELLOW("yellow","黄(当前日期-截止日期<=7)",-7),
//            GREEN("green","绿(当前日期-截止日期>7)",7),
//            BLUE("blue","蓝(截止日期为空）",0);
            if (StringUtils.isNotBlank(vo.getDifferenceDays())) {
                dfds = Double.valueOf(vo.getDifferenceDays()).intValue();
                if (dfds <= 0) {
                    vo.setTimeColor("red");
                }
                if (dfds <= 1 && dfds > 0) {
                    vo.setTimeColor("yellow");
                }
                if (dfds > 1) {
                    vo.setTimeColor("blue");
                }
                //拼接时间描述
                if (dfds >= 0) {
                    vo.setDifferenceDays("剩" + dfds + "天");
                }
                if (dfds < 0) {
                    vo.setDifferenceDays("超" + (-dfds) + "天");
                }
            }
            if (StringUtils.isBlank(vo.getDeadline())) {
                vo.setTimeColor("blue");
            }
            //4.caseType 翻译 案件类型:1简易程序  2普通程序  3快速办理
            vo.setCaseType(CaseTypeEnum.getValueByCode(vo.getCaseType()));
            /*if (Constant.STRING_1.equals(vo.getCaseType())) {
                vo.setCaseType("简易程序");
            } else if (Constant.STRING_2.equals(vo.getCaseType())) {
                vo.setCaseType("一般程序");
            }
            if (Constant.STRING_3.equals(vo.getCaseType())) {
                vo.setCaseType("快速办理");
            }*/
            // 多案由处理
            example.clear();
            example.createCriteria().andEqualTo("caseId", vo.getCaseId()).andEqualTo("status", "1");
            List<CaseReasonMainRecord> records = caseReasonMainRecordMapper.selectByExample(example);
            StringJoiner stringJoiner = new StringJoiner(";");
            for (CaseReasonMainRecord record : records) {
                stringJoiner.add(record.getCaseReasonName());
            }
            vo.setCaseReason(stringJoiner.toString());
        }
        return list;
    }

    @Override
    public WaitPageEachColorNumVo getEachColorNum(AuditQueryPageDto auditQueryPageDto) {
        //获取当前用户
        UserDTO userDTO = UserUtil.getUserInfo();
        auditQueryPageDto.setUserId(userDTO.getUserId().toString());
        //是否联合法制审核为空默认为0
        if (StringUtils.isBlank(auditQueryPageDto.getIsApprovalCenter())) {
            auditQueryPageDto.setIsApprovalCenter("0");
        }
        WaitPageEachColorNumVo waitPageEachColorNumVo = null;
        // 联合法制审核 查询
        String one = "1";
        if (StringUtils.isNotBlank(auditQueryPageDto.getIsApprovalCenter()) && one.equals(auditQueryPageDto.getIsApprovalCenter())) {
            waitPageEachColorNumVo = caseApprovalWaitRecordMapper.getEachColorNumCenter(auditQueryPageDto);
        } else {
            waitPageEachColorNumVo = caseApprovalWaitRecordMapper.getEachColorNum(auditQueryPageDto);
        }
        waitPageEachColorNumVo.setTotal(waitPageEachColorNumVo.getBlueNum() + waitPageEachColorNumVo.getYellowNum() + waitPageEachColorNumVo.getRedNum());
        return waitPageEachColorNumVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> doAgreeAudit(ApprovalAgreeAuditDto approvalAuditDto) {
        //默认不是最后最后审批节点
        boolean isLast = false;
        //读取当前用户，获取当前审批环节
        UserDTO userDTO = UserUtil.getUserInfo();
        String partyId = approvalAuditDto.getPartyId();
        String docId = approvalAuditDto.getDocId();
        List<CaseApprovalWaitRecord> currentRecord = null;
        List<CaseDocumentRecord> caseDocumentRecords = null;
        if (StringUtils.isNotBlank(docId)) {
            Example waitExample = new Example(CaseApprovalWaitRecord.class);
            waitExample.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("docId", docId);
            currentRecord = caseApprovalWaitRecordMapper.selectByExample(waitExample);
            if (CollUtil.isEmpty(currentRecord)) {
                throw new BusinessException("当前无审批任务");
            }
            //当当前待审批记录不为空时执行
            Example docRecordExample = new Example(CaseDocumentRecord.class);
            docRecordExample.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("id", docId).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId());
            caseDocumentRecords = caseDocumentRecordMapper.selectByExample(docRecordExample);
            if (Constant.STRING_1.equals(caseDocumentRecords.get(0).getIsModifyRecord())) {
                //如果是变更文书,走修改文书审批
                return doAgreeAuditOfModifyRecord(approvalAuditDto);
            }
        }
        if (org.springframework.util.ObjectUtils.isEmpty(currentRecord)) {
            Example example = new Example(CaseApprovalWaitRecord.class);
            Example.Criteria criteria = example.createCriteria();
            if (StringUtils.isBlank(partyId)) {
                criteria.andEqualTo("caseId", approvalAuditDto.getCaseId());
            } else {
                criteria.andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("partyId", partyId);
            }
            if (StringUtils.isNotBlank(approvalAuditDto.getDocumentCatalogCode())) {
                criteria.andEqualTo("documentId", approvalAuditDto.getDocumentCatalogCode());
            }
            currentRecord = caseApprovalWaitRecordMapper.selectByExample(example);
        }
        //如果待审批记录不存在 则提示无审批记录
        if (currentRecord.isEmpty()) {
            throw new BusinessException("当前无审批任务");
        }
        //校验登录人的id是否为审批人
        String userId = userDTO.getUserId().toString();
        if (!currentRecord.get(0).getApprovalUserId().contains(userId)) {
            throw new BusinessException("当前待审批记录，已被其他人审批，请刷新当前页面！");
        }
        //获取文书记录
        if (org.springframework.util.ObjectUtils.isEmpty(caseDocumentRecords)) {
            docId = currentRecord.get(0).getDocId();
            Example exampleDocRecord = new Example(CaseDocumentRecord.class);
            if (StringUtils.isNotBlank(docId)) {
                exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId()).andEqualTo("id", docId);
            } else {
                if (StringUtils.isBlank(partyId)) {
                    exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId()).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                } else {
                    exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId()).andEqualTo("partyId", partyId).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                }
            }
            caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDocRecord);
            if (Constant.STRING_1.equals(caseDocumentRecords.get(0).getIsModifyRecord())) {
                //如果是变更文书,走修改文书审批
                approvalAuditDto.setDocId(caseDocumentRecords.get(0).getId());
                return doAgreeAuditOfModifyRecord(approvalAuditDto);
            }
        }


        //删除待审批节点
        int del = caseApprovalWaitRecordMapper.deleteByPrimaryKey(currentRecord.get(0).getId());
        // 校验审批权限，检验当前登录人id是否在待审批id
        /*String approvalUserIds=currentRecord.get(0).getApprovalUserId();
        String[] approvalUserArr=approvalUserIds.split(",");
        List<String> approvalUserList=Arrays.asList(approvalUserArr);
        String userId=userDTO.getUserId().toString();
        if(!approvalUserList.contains(userId)){
            throw new BusinessException("当前任务已审批！");
        }*/
        //查询案件信息
        String caseId = approvalAuditDto.getCaseId();
        CaseMainInfoVo caseMainInfo = caseMainInfoMapper.selectCaseMainInfo(caseId);
        //判断是否需要滚流程
        String documentCatalogCode = currentRecord.get(0).getDocumentId();
        boolean isCaseSourceRoll = getIsCaseSourceRoll(caseMainInfo, documentCatalogCode);
        Map<String, Object> result = new HashMap<>(8);
        //已审批通过记录保存
        int completeIn = getCompleteIn(approvalAuditDto, currentRecord);
        //获取审批relation
        CaseApprovalFlowRelation caseApprovalFlowRelation = caseDocuApprovalFolwRelationMapper.selectByPrimaryKey(currentRecord.get(0).getFlowRelationId());
        if (caseApprovalFlowRelation == null) {
            throw new BusinessException("未匹配到审批流关联配置信息-flowRelationId:" + currentRecord.get(0).getFlowRelationId());
        }
        Example example1 = new Example(CaseApprovalFlowRelation.class);
        example1.createCriteria().andEqualTo("documentCatalogCode", caseApprovalFlowRelation.getDocumentCatalogCode()).andEqualTo("approvalFlowVerson", caseApprovalFlowRelation.getApprovalFlowVerson()).andEqualTo("approvalFlowId", caseApprovalFlowRelation.getApprovalFlowId());
        List<CaseApprovalFlowRelation> caseApprovalFlowRelations = caseDocuApprovalFolwRelationMapper.selectByExample(example1);

        //是最后一个节点
        Map<String, Object> result1 = finalNodeProcess(approvalAuditDto, currentRecord, del, completeIn, caseApprovalFlowRelations, result, caseDocumentRecords, partyId, approvalAuditDto.getCaseAssistId());
        if (result1 != null) {
            sendDingAuditFinishMsg(currentRecord, "YES");
            //是生态条线与案件调查报告审批通过插入数据（待分配）
            //String documentCatalogCode1 =  caseDocumentRecords.stream().filter(e-> DocumentStatusEnum.CHECKING.getCode().equals(e.getDocumentApprovalStatus())).collect(Collectors.toList()).get(0).getDocumentCatalogCode();
            if (Constant.ECOLOGICAL_LINE_CODE.equals(caseMainInfo.getCaseTerritoryCode()) && Constant.ECOLOGICAL_INVESTIGATION_REPORT.equals(currentRecord.get(0).getDocumentId())) {
                //涉刑移送不需要走待分配
                CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(caseId);
                if (!Constant.STRING_1.equals(caseMainDetailInfo.getHandleConclusion())) {
                    caseDistributionRecordService.insertDistribution(caseId);
                }
            }
            if (!isCaseSourceRoll) {
                return result;
            }
            return result1;
        }
        //查询配置表
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(currentRecord.get(0), "");
        int sortNum = Integer.valueOf(currentRecord.get(0).getApprovalNum());
        //不是最后一个节点，下一审批人必传
        if (StringUtils.isBlank(approvalAuditDto.getNextHandler()) && caseApprovalFlowRelations.size() > sortNum) {
            throw new BusinessException("系统异常，下一环节处理人必选！");
        }
        // 下一环节待审批信息
        ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(caseDocumentRecords.get(0).getDocumentCatalogCode());
        //判断审批记录是否存在
        boolean isExist = false;
        if (ObjectUtil.isNotEmpty(docId) && DocumentKindEnum.DOC_KIND_DK1BZGZSPB.getCode().equals(detailByDocumentCatalogCode.getDocumentKindCode())) {
            isExist = checkCaseApprovalWaitRecordIsExistByDocumentId(caseId, caseDocumentRecords.get(0).getId());
        } else {
            isExist = checkCaseApprovalWaitRecordIsExist(caseId, documentCatalogCode, partyId);
        }
        //boolean isExist=checkCaseApprovalWaitRecordIsExist(approvalAuditDto.getCaseId(),currentRecord.get(0).getDocumentId(),partyId);
        if (isExist) {
            throw new BusinessException("审批通过失败，生成待审批记录已存在，请勿重复提交!");
        }
        CaseApprovalWaitRecord nextRecord = new CaseApprovalWaitRecord();
        BeanUtils.copyProperties(currentRecord.get(0), nextRecord);
        if (StringUtils.isNotBlank(nextFlow.get(0).getApprovalTerm())) {
            Integer term = nextFlow.get(0).getApprovalTerm().contains("天") ? new Integer(nextFlow.get(0).getApprovalTerm().substring(0, nextFlow.get(0).getApprovalTerm().length() - 1)) : new Integer(nextFlow.get(0).getApprovalTerm());
            nextRecord.setApprovalCurrentLimitTime(term);
            nextRecord.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
        }
        nextRecord.setId(StringUtils.uuid());
        JSONObject baseInfoRequest = new JSONObject();
        if (StringUtils.isBlank(approvalAuditDto.getNextHandler())) {
            CaseMainInfo mainInfo = new CaseMainInfo();
            BeanUtils.copyProperties(caseMainInfo, mainInfo);
            NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(mainInfo, nextFlow.get(0).getApprovalRole(), documentCatalogCode);
            nextRecord.setApprovalUserId(vo.getUserId());
            approvalAuditDto.setNextHandler(vo.getUserId());
            approvalAuditDto.setAutoTime(vo.getAutoTime());
            approvalAuditDto.setIsAutoApproval(vo.getIsAutoApproval());
        } else {
            nextRecord.setApprovalUserId(approvalAuditDto.getNextHandler());
            if (Constant.STRING_1.equals(approvalAuditDto.getIsAutoApproval())) {
                CaseMainInfo mainInfo = new CaseMainInfo();
                BeanUtils.copyProperties(caseMainInfo, mainInfo);
                NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(mainInfo, nextFlow.get(0).getApprovalRole(), documentCatalogCode);
                approvalAuditDto.setNextHandler(vo.getUserId());
                approvalAuditDto.setAutoTime(vo.getAutoTime());
                approvalAuditDto.setIsAutoApproval(vo.getIsAutoApproval());
            }
        }
        List<String> userIds = new ArrayList<>();
        userIds.addAll(Arrays.asList(approvalAuditDto.getNextHandler().split(",")));
        baseInfoRequest.put("userIds", userIds);
        if (StringUtils.isNotBlank(approvalAuditDto.getApprovalCenterOrgCode())) {
            List<String> orgCodes = new ArrayList<>();
            orgCodes.add(approvalAuditDto.getApprovalCenterOrgCode());
            baseInfoRequest.put("orgCodes", orgCodes);
        }
        //baseInfoRequest.put("orgCodes",approvalAuditDto.getApprovalCenterOrgCode());
        List<ZfPeopleBaseInfoVO> baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userIds", userIds);
        if (null != userIds && userIds.size() > 0) {
            List<String> userNameList = memberUserSignMapper.selectUserNameList(paramMap);
            if (null != userNameList && userNameList.size() > 0) {
                StringJoiner stringJoiner = new StringJoiner(",");
                for (String userName : userNameList) {
                    stringJoiner.add(userName);
                }
                nextRecord.setApprovalUserName(stringJoiner.toString());
            } else {
                nextRecord.setApprovalUserName("");
            }
        } else {
            nextRecord.setApprovalUserName("");
        }
        nextRecord.setApprovalNum(nextFlow.get(0).getApprovalOrderNum());
        nextRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
        nextRecord.setFlowRelationId(nextFlow.get(0).getId());
        if (StringUtils.isNotBlank(approvalAuditDto.getApprovalCenterOrgName())) {
            nextRecord.setApprovalOrgName(approvalAuditDto.getApprovalCenterOrgName());
            if (approvalAuditDto.getApprovalCenterOrgName().contains("联合法制审核")) {
                String approvalCenterOrgName = approvalAuditDto.getApprovalCenterOrgName();
                approvalCenterOrgName = approvalCenterOrgName.substring(approvalCenterOrgName.indexOf("（") + 1, approvalCenterOrgName.indexOf("）"));
                nextRecord.setApprovalOrgName(approvalCenterOrgName);
                nextRecord.setApprovalOrgCode(approvalAuditDto.getApprovalCenterOrgCode());
            }
        } else {
            nextRecord.setApprovalOrgCode(caseMainInfo.getCaseOrgCode());
        }
        nextRecord.setPartyId(partyId);
        nextRecord.setAutoTime(approvalAuditDto.getAutoTime());
        nextRecord.setIsAutoApproval(approvalAuditDto.getIsAutoApproval());
        int nextIn = caseApprovalWaitRecordMapper.insert(nextRecord);
        Boolean f = (del == 1 && completeIn == 1 && nextIn == 1);
        if (f) {
            // 生成审批后文书
            String approvalStatus = DocumentStatusEnum.CHECKING.getCode();
            makeDoc(currentRecord.get(0).getFlowRelationId(), approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), caseDocumentRecords.get(0), approvalAuditDto.getOpinion(), isLast, approvalStatus, partyId, approvalAuditDto.getCaseAssistId(), currentRecord.get(0).getIsEditApproval(), currentRecord.get(0).getDocId(), approvalAuditDto.getExceptionCaseDocumentSerialKey());
            // 下一审批人,新审批钉钉提醒
            sendNewAuditDingMsg(approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), nextRecord.getApprovalCurrentLimitTime(), userIds);

            //工作台-消息提醒
           /* ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            sendNewAuditPcMsg(caseId,caseMainInfo.getCaseOrgName(),documentCatalogCode,configBusiParamDocumentInfo.getDocumentCatalogName(),nextRecord,caseMainInfo.getCaseOrgCode(),userIds);
*/
            if (!isCaseSourceRoll) {
                result.put("success", "true");
                return result;
            }
            result.put("caseId", approvalAuditDto.getCaseId());
            //速结程序判断下个节点是否自动审批
            if (Constant.STRING_3.equals(caseMainInfo.getCaseType())) {
                String closeSignal = "";
                ApprovalGeneralSubmitDto dto = new ApprovalGeneralSubmitDto();
                BeanUtils.copyProperties(approvalAuditDto, dto);
                dto.setDocumentCatalogCode(currentRecord.get(0).getDocumentId());
                ApprovalAgreeAuditDto approvalAgreeAuditDto = getApprovalAgreeAuditDto(dto);
                approvalAgreeAuditDto.setNowHandler(dto.getNextHandler());
                if (Constant.STRING_1.equals(approvalAgreeAuditDto.getIsAutoApproval())) {
                    for (int i = 0; i < 4; i++) {
                        //如果下个环节是自动审批
                        if (Constant.STRING_1.equals(approvalAgreeAuditDto.getIsAutoApproval())) {
                            Long autoTime = Long.valueOf(approvalAgreeAuditDto.getAutoTime());
                            try {
                                Thread.sleep(autoTime * 1000);
                                //Thread.sleep(autoTime);
                                Map<String, Object> agreeResult = doAgreeAuditAuto(approvalAgreeAuditDto);
                                closeSignal = MapUtils.getString(agreeResult, "closeSignal", "");
                                //result.put("closeSignal", "CLOSE-TRIGGER-APPROVAL-PASS");
                                if ("CLOSE-TRIGGER-APPROVAL-PASS".equals(closeSignal)) {
                                    cfRedisRepository.set("IS_APPROVAL_AUTO_PASS" + dto.getCaseId(), "true");
                                    break;
                                }
                                String nowHandler = approvalAgreeAuditDto.getNextHandler();
                                approvalAgreeAuditDto = getApprovalAgreeAuditDto(dto);
                                approvalAgreeAuditDto.setNowHandler(nowHandler);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            cfRedisRepository.set("IS_APPROVAL_AUTO_PASS" + dto.getCaseId(), "true");
                            break;
                        }
                    }

                }
            }
            return result;
        } else {
            throw new BusinessException("审批通过数据处理时出现异常");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> doAgreeAuditAuto(ApprovalAgreeAuditDto approvalAuditDto) {
        //默认不是最后最后审批节点
        boolean isLast = false;
        //读取当前用户，获取当前审批环节
        //UserDTO userDTO =approvalAuditDto.getUserDTO();
        String partyId = approvalAuditDto.getPartyId();
        Example example = new Example(CaseApprovalWaitRecord.class);
        if (StringUtils.isBlank(partyId)) {
            example.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId());
        } else {
            example.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("partyId", partyId);
        }
        List<CaseApprovalWaitRecord> currentRecord = caseApprovalWaitRecordMapper.selectByExample(example);
        //如果待审批记录不存在 则提示无审批记录
        if (currentRecord.isEmpty()) {
            throw new BusinessException("当前无审批任务");
        }
        //删除待审批节点
        int del = caseApprovalWaitRecordMapper.deleteByPrimaryKey(currentRecord.get(0).getId());
        // 校验审批权限，检验当前登录人id是否在待审批id
        /*String approvalUserIds=currentRecord.get(0).getApprovalUserId();
        String[] approvalUserArr=approvalUserIds.split(",");
        List<String> approvalUserList=Arrays.asList(approvalUserArr);
        String userId=userDTO.getUserId().toString();
        if(!approvalUserList.contains(userId)){
            throw new BusinessException("当前任务已审批！");
        }*/
        //查询案件信息
        String caseId = approvalAuditDto.getCaseId();
        CaseMainInfoVo caseMainInfo = caseMainInfoMapper.selectCaseMainInfo(caseId);
        //判断是否需要滚流程
        String documentCatalogCode = currentRecord.get(0).getDocumentId();
        boolean isCaseSourceRoll = getIsCaseSourceRoll(caseMainInfo, documentCatalogCode);
        Map<String, Object> result = new HashMap<>(8);
        //已审批通过记录保存
        int completeIn = getCompleteInAuto(approvalAuditDto, currentRecord);
        //获取审批relation
        CaseApprovalFlowRelation caseApprovalFlowRelation = caseDocuApprovalFolwRelationMapper.selectByPrimaryKey(currentRecord.get(0).getFlowRelationId());
        if (caseApprovalFlowRelation == null) {
            throw new BusinessException("未匹配到审批流关联配置信息-flowRelationId:" + currentRecord.get(0).getFlowRelationId());
        }
        Example example1 = new Example(CaseApprovalFlowRelation.class);
        example1.createCriteria().andEqualTo("documentCatalogCode", caseApprovalFlowRelation.getDocumentCatalogCode()).andEqualTo("approvalFlowVerson", caseApprovalFlowRelation.getApprovalFlowVerson()).andEqualTo("approvalFlowId", caseApprovalFlowRelation.getApprovalFlowId());
        List<CaseApprovalFlowRelation> caseApprovalFlowRelations = caseDocuApprovalFolwRelationMapper.selectByExample(example1);
        //获取文书记录
        Example exampleDocRecord = new Example(CaseDocumentRecord.class);
        if (StringUtils.isBlank(partyId)) {
            exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId()).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        } else {
            exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId()).andEqualTo("partyId", partyId).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        }
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDocRecord);
        //是最后一个节点
        Map<String, Object> result1 = finalNodeProcessAuto(approvalAuditDto, currentRecord, del, completeIn, caseApprovalFlowRelations, result, caseDocumentRecords, partyId, approvalAuditDto.getCaseAssistId());
        if (result1 != null) {
            // 发送审批完成,提交人钉钉提醒
            //sendDingAuditFinish(currentRecord,"YES");
            sendDingAuditFinishMsg(currentRecord, "YES");

            //工作台-消息提醒
            List<String> userIds = new ArrayList<>();
            userIds.add(currentRecord.get(0).getAddUserId());
            ConfigBusiParamDocumentInfo catalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            sendAuditFinishPassPcMsg(caseId, documentCatalogCode, catalogCode.getDocumentCatalogName(), currentRecord.get(0), caseMainInfo.getCaseOrgCode(), userIds);

            //是生态条线与案件调查报告审批通过插入数据（待分配）
            //String documentCatalogCode1 =  caseDocumentRecords.stream().filter(e-> DocumentStatusEnum.CHECKING.getCode().equals(e.getDocumentApprovalStatus())).collect(Collectors.toList()).get(0).getDocumentCatalogCode();
            if (Constant.ECOLOGICAL_LINE_CODE.equals(caseMainInfo.getCaseTerritoryCode()) && Constant.ECOLOGICAL_INVESTIGATION_REPORT.equals(currentRecord.get(0).getDocumentId())) {
                caseDistributionRecordService.insertDistribution(caseId);
            }
            // 加上大综合的消息发送
            //taskCenterUrl+saveEntMessage
            Example example3 = new Example(CasePartiesRecord.class);
            Example.Criteria criteria = example3.createCriteria();
            criteria.andEqualTo("caseId", caseId).andEqualTo("status", Constant.STRING_1).andEqualTo("partyType", Constant.STRING_2);
            if (StringUtils.isNotBlank(partyId)) {
                criteria.andEqualTo("partyId", partyId);
            }
            List<CasePartiesRecord> casePartiesRecords = casePartiesRecordMapper.selectByExample(example3);
            if (ObjectUtils.isNotEmpty(casePartiesRecords) && casePartiesRecords.size() > 0) {
                ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
                String documentKindCode = detailByDocumentCatalogCode.getDocumentKindCode();
                String documentUrl = caseDocumentRecords.get(0).getDocumentUrl();
                String[] relationDocumentCatalogCode = detailByDocumentCatalogCode.getRelationDocumentCatalogCode().split(",");
                PunishMsgParams punishMsgParams = new PunishMsgParams();
                if (Constant.STRING_KIND_CODE_ZLGZTZS.equals(documentKindCode)) {
                    punishMsgParams.setContent("您企业收到一份整改通知书");
                    punishMsgParams.setTitle("责令整改通知书");
                    punishMsgParams.setSourceUrl(documentUrl);
                    punishMsgParams.setType(Constant.STRING_4);
                }
                if (Constant.STRING_KIND_CODE_CFGZSPB.equals(documentKindCode)) {
                    punishMsgParams.setContent("您企业收到一份处罚告知书");
                    punishMsgParams.setTitle("处罚告知书");
                    Example exampleDocumentRecord = new Example(CaseDocumentRecord.class);
                    if (StringUtils.isBlank(partyId)) {
                        exampleDocumentRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", relationDocumentCatalogCode[0]).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                    } else {
                        exampleDocumentRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", relationDocumentCatalogCode[0]).andEqualTo("partyId", partyId).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                    }
                    List<CaseDocumentRecord> exampleDocumentRecordList = caseDocumentRecordMapper.selectByExample(exampleDocRecord);
                    punishMsgParams.setSourceUrl(exampleDocumentRecordList.get(0).getDocumentUrl());
                    punishMsgParams.setType(Constant.STRING_5);
                }
                if (Constant.STRING_KIND_CODE_CFJDSPB.equals(documentKindCode)) {
                    punishMsgParams.setContent("您企业收到一份处罚决定书");
                    punishMsgParams.setTitle("处罚决定书");
                    Example exampleDocumentRecord = new Example(CaseDocumentRecord.class);
                    if (StringUtils.isBlank(partyId)) {
                        exampleDocumentRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", relationDocumentCatalogCode[0]).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                    } else {
                        exampleDocumentRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", relationDocumentCatalogCode[0]).andEqualTo("partyId", partyId).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                    }
                    List<CaseDocumentRecord> exampleDocumentRecordList = caseDocumentRecordMapper.selectByExample(exampleDocRecord);
                    punishMsgParams.setSourceUrl(exampleDocumentRecordList.get(0).getDocumentUrl());
                    punishMsgParams.setType(Constant.STRING_6);
                }
                punishMsgParams.setUniCode(casePartiesRecords.get(0).getPartyIdentityCode());
                punishMsgParams.setDeptName(caseMainInfo.getCaseOrgName());
                punishMsgParams.setSendTime(new Date());
                comprehensiveMsg(punishMsgParams);
            }
            if (!isCaseSourceRoll) {
                return result;
            }
            return result1;
        }
        //查询配置表
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(currentRecord.get(0), "");
        int sortNum = Integer.valueOf(currentRecord.get(0).getApprovalNum());
        //不是最后一个节点，下一审批人必传
        if (StringUtils.isBlank(approvalAuditDto.getNextHandler()) && caseApprovalFlowRelations.size() > sortNum) {
            throw new BusinessException("系统异常，下一环节处理人必选！");
        }
        // 下一环节待审批信息
        //判断审批记录是否存在
        boolean isExist = checkCaseApprovalWaitRecordIsExist(approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), partyId);
        if (isExist) {
            throw new BusinessException("审批通过失败，生成待审批记录已存在，请勿重复提交!");
        }
        CaseApprovalWaitRecord nextRecord = new CaseApprovalWaitRecord();
        BeanUtils.copyProperties(currentRecord.get(0), nextRecord);
        if (StringUtils.isNotBlank(nextFlow.get(0).getApprovalTerm())) {
            Integer term = nextFlow.get(0).getApprovalTerm().contains("天") ? new Integer(nextFlow.get(0).getApprovalTerm().substring(0, nextFlow.get(0).getApprovalTerm().length() - 1)) : new Integer(nextFlow.get(0).getApprovalTerm());
            nextRecord.setApprovalCurrentLimitTime(term);
            nextRecord.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
        }
        nextRecord.setId(StringUtils.uuid());
        JSONObject baseInfoRequest = new JSONObject();
        if (StringUtils.isBlank(approvalAuditDto.getNextHandler())) {
            CaseMainInfo mainInfo = new CaseMainInfo();
            BeanUtils.copyProperties(caseMainInfo, mainInfo);
            NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(mainInfo, nextFlow.get(0).getApprovalRole(), documentCatalogCode);
            nextRecord.setApprovalUserId(vo.getUserId());
            approvalAuditDto.setNextHandler(vo.getUserId());
            approvalAuditDto.setAutoTime(vo.getAutoTime());
            approvalAuditDto.setIsAutoApproval(vo.getIsAutoApproval());
        } else {
            nextRecord.setApprovalUserId(approvalAuditDto.getNextHandler());
            if (Constant.STRING_1.equals(approvalAuditDto.getIsAutoApproval())) {
                CaseMainInfo mainInfo = new CaseMainInfo();
                BeanUtils.copyProperties(caseMainInfo, mainInfo);
                NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(mainInfo, nextFlow.get(0).getApprovalRole(), documentCatalogCode);
                approvalAuditDto.setNextHandler(vo.getUserId());
                approvalAuditDto.setAutoTime(vo.getAutoTime());
                approvalAuditDto.setIsAutoApproval(vo.getIsAutoApproval());
            }
        }
        List<String> userIds = new ArrayList<>();
        userIds.addAll(Arrays.asList(approvalAuditDto.getNextHandler().split(",")));
        baseInfoRequest.put("userIds", userIds);
        if (StringUtils.isNotBlank(approvalAuditDto.getApprovalCenterOrgCode())) {
            List<String> orgCodes = new ArrayList<>();
            orgCodes.add(approvalAuditDto.getApprovalCenterOrgCode());
            baseInfoRequest.put("orgCodes", orgCodes);
        }
        //baseInfoRequest.put("orgCodes",approvalAuditDto.getApprovalCenterOrgCode());
        List<ZfPeopleBaseInfoVO> baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userIds", userIds);
        if (null != userIds && userIds.size() > 0) {
            List<String> userNameList = memberUserSignMapper.selectUserNameList(paramMap);
            if (null != userNameList && userNameList.size() > 0) {
                StringJoiner stringJoiner = new StringJoiner(",");
                for (String userName : userNameList) {
                    stringJoiner.add(userName);
                }
                nextRecord.setApprovalUserName(stringJoiner.toString());
            } else {
                nextRecord.setApprovalUserName("");
            }
        } else {
            nextRecord.setApprovalUserName("");
        }
        nextRecord.setApprovalNum(nextFlow.get(0).getApprovalOrderNum());
        nextRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
        nextRecord.setFlowRelationId(nextFlow.get(0).getId());
        if (StringUtils.isNotBlank(approvalAuditDto.getApprovalCenterOrgName())) {
            nextRecord.setApprovalOrgName(approvalAuditDto.getApprovalCenterOrgName());
            if (approvalAuditDto.getApprovalCenterOrgName().contains("联合法制审核")) {
                String approvalCenterOrgName = approvalAuditDto.getApprovalCenterOrgName();
                approvalCenterOrgName = approvalCenterOrgName.substring(approvalCenterOrgName.indexOf("（") + 1, approvalCenterOrgName.indexOf("）"));
                nextRecord.setApprovalOrgName(approvalCenterOrgName);
                nextRecord.setApprovalOrgCode(approvalAuditDto.getApprovalCenterOrgCode());
            }
        } else {
            nextRecord.setApprovalOrgCode(caseMainInfo.getCaseOrgCode());
        }
        nextRecord.setPartyId(partyId);
        nextRecord.setAutoTime(approvalAuditDto.getAutoTime());
        nextRecord.setIsAutoApproval(approvalAuditDto.getIsAutoApproval());
        nextRecord.setAddTime(new Date());
        int nextIn = caseApprovalWaitRecordMapper.insert(nextRecord);
        Boolean f = (del == 1 && completeIn == 1 && nextIn == 1);
        if (f) {
            // 生成审批后文书
            String approvalStatus = DocumentStatusEnum.CHECKING.getCode();
            makeDocAuto(currentRecord.get(0).getFlowRelationId(), approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), caseDocumentRecords.get(0), approvalAuditDto.getOpinion(), isLast, approvalStatus, partyId, approvalAuditDto.getCaseAssistId(), approvalAuditDto.getNowHandler());
            if (!isCaseSourceRoll) {
                result.put("success", "true");
                return result;
            }
            result.put("caseId", approvalAuditDto.getCaseId());
            /*if(Constant.STRING_1.equals(approvalAuditDto.getIsAutoApproval())&&Constant.STRING_3.equals(caseMainInfo.getCaseType())) {
                //自动审批
                doAutoApproval(approvalAuditDto.getAutoTime(),caseId,documentCatalogCode,caseMainInfo,approvalAuditDto.getUserDTO());
            }*/
            return result;
        } else {
            throw new BusinessException("审批通过数据处理时出现异常");
        }

    }

    /**
     * 审批是否展示公示详情 1 是 , 0 否
     *
     * @param dto
     * @return {@link String}
     * @author liyafeng
     * @date 2022/12/22
     */
    @Override
    public String getApprovalIsShowPublicDetail(ApprovalIsShowPublicDetailDto dto) {
        String isShow = Constant.STRING_0;
        try {
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(dto.getDocumentCatalogCode());
            if (null != configBusiParamDocumentInfo) {
                if (Constant.STRING_KIND_CODE_CFJDSPB.equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
                    CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(dto.getCaseId());
                    if (Constant.STRING_2.equals(caseMainInfo.getHandleType())) {
                        //分别处罚
                        Example example = new Example(CaseMainDetailAuxiliaryInfo.class);
                        example.createCriteria().andEqualTo("caseId", dto.getCaseId()).andEqualTo("partyId", dto.getPartyId());
                        List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfos = mainDetailAuxiliaryInfoMapper.selectByExample(example);
                        if (CollUtil.isNotEmpty(caseMainDetailAuxiliaryInfos)) {
                            CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = caseMainDetailAuxiliaryInfos.get(0);
                            if (Constant.STRING_1.equals(caseMainDetailAuxiliaryInfo.getInvestConclusion())) {
                                isShow = Constant.STRING_1;
                            }
                        }
                    } else {
                        //合并处罚
                        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(dto.getCaseId());
                        if (Constant.STRING_1.equals(caseMainDetailInfo.getInvestConclusion())) {
                            isShow = Constant.STRING_1;
                        }

                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return isShow;
    }

    @Override
    public Map<String, Object> documentGeneralSubmitNew(ApprovalGeneralSubmitDto dto) {
        //1.获取案件信息
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(dto.getCaseId());
        String handleType = caseMainInfo.getHandleType();
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(dto.getDocumentCatalogCode());
        //2.更新文书记录表
        CaseDocumentRecord caseDocumentRecord = updateDocumentRecord(dto, configBusiParamDocumentInfo);
        //3.保存待审批记录
        CaseApprovalWaitRecord caseApprovalWaitRecord = saveCaseApprovalWaitRecord(dto, caseMainInfo, configBusiParamDocumentInfo);

        //4.生成发起人完成记录，审批序号设为零。供审批日志链使用，userId设为空防止我已审批查出来
        saveCaseApprovalCompleteRecord(dto, caseApprovalWaitRecord);
        Map<String, Object> result = new HashMap<>(8);
        result.put("documentId", caseDocumentRecord.getId());
        // 5.生成文书
        UserDTO userDTO = UserUtil.getUserInfo();
        setUnderTakeOpinion(dto.getCaseId(), dto.getDocumentCatalogCode(), dto.getOpinion(), caseDocumentRecord, userDTO, dto.getPartyId(), dto.getIsEditApproval(), dto.getDocId());
        result.put("workId", dto.getCaseId());
        String documentLinkObjectType = configBusiParamDocumentInfo.getDocumentLinkObjectType();
        if (Constant.STRING_2.equals(handleType) && Constant.STRING_2.equals(documentLinkObjectType)) {
            result.put("workSubId", dto.getPartyId());
        }
        result.put("closeSignal", "CLOSE-TRIGGER-APPROVAL");
        result.put("documentCatalogCode", dto.getDocumentCatalogCode());
        if (StringUtils.isNotBlank(dto.getCaseAssistId())) {
            result.put("workAssistId", dto.getCaseAssistId());
        }
        return result;
    }

    /**
     * 审批通过-new
     *
     * @param approvalAuditDto
     * @return {@link Map< Object, Object>}
     * @author liyafeng
     * @date 2023/1/4
     */
    @Override
    public Map<String, Object> doAgreeAuditNew(ApprovalAgreeAuditDto approvalAuditDto) {
        //默认不是最后最后审批节点
        boolean isLast = false;
        //获取当前待审批记录
        List<CaseApprovalWaitRecord> currentRecordList = getCurrentRecordList(approvalAuditDto);
        //如果待审批记录不存在 则提示无审批记录
        if (currentRecordList.isEmpty()) {
            throw new BusinessException("当前无审批任务");
        }
        //删除待审批节点
        int del = caseApprovalWaitRecordMapper.deleteByPrimaryKey(currentRecordList.get(0).getId());

        //查询案件信息
        String caseId = approvalAuditDto.getCaseId();
        CaseMainInfoVo caseMainInfo = caseMainInfoMapper.selectCaseMainInfo(caseId);
        //判断案源是否需要滚流程
        String documentCatalogCode = currentRecordList.get(0).getDocumentId();
        boolean isCaseSourceRoll = getIsCaseSourceRoll(caseMainInfo, documentCatalogCode);
        Map<String, Object> result = new HashMap<>(8);
        //已审批通过记录保存
        int completeIn = getCompleteIn(approvalAuditDto, currentRecordList);
        //获取审批relation
        CaseApprovalFlowRelation caseApprovalFlowRelation = caseDocuApprovalFolwRelationMapper.selectByPrimaryKey(currentRecordList.get(0).getFlowRelationId());
        if (caseApprovalFlowRelation == null) {
            throw new BusinessException("未匹配到审批流关联配置信息-flowRelationId:" + currentRecordList.get(0).getFlowRelationId());
        }
        Example example1 = new Example(CaseApprovalFlowRelation.class);
        example1.createCriteria().andEqualTo("documentCatalogCode", caseApprovalFlowRelation.getDocumentCatalogCode()).andEqualTo("approvalFlowVerson", caseApprovalFlowRelation.getApprovalFlowVerson()).andEqualTo("approvalFlowId", caseApprovalFlowRelation.getApprovalFlowId());
        List<CaseApprovalFlowRelation> caseApprovalFlowRelations = caseDocuApprovalFolwRelationMapper.selectByExample(example1);
        //获取文书记录
        Example exampleDocRecord = new Example(CaseDocumentRecord.class);
        String partyId = approvalAuditDto.getPartyId();
        if (StringUtils.isBlank(partyId)) {
            exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", currentRecordList.get(0).getDocumentId()).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        } else {
            exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", currentRecordList.get(0).getDocumentId()).andEqualTo("partyId", partyId).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        }
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDocRecord);
        //是最后一个节点
        Map<String, Object> result1 = finalNodeProcess(approvalAuditDto, currentRecordList, del, completeIn, caseApprovalFlowRelations, result, caseDocumentRecords, partyId, approvalAuditDto.getCaseAssistId());
        if (result1 != null) {
            // 发送审批完成,提交人钉钉提醒
            //sendDingAuditFinish(currentRecord,"YES");
            sendDingAuditFinishMsg(currentRecordList, "YES");

            //工作台-消息提醒
            List<String> userIds = new ArrayList<>();
            userIds.add(currentRecordList.get(0).getAddUserId());
            ConfigBusiParamDocumentInfo catalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            sendAuditFinishPassPcMsg(caseId, documentCatalogCode, catalogCode.getDocumentCatalogName(), currentRecordList.get(0), caseMainInfo.getCaseOrgCode(), userIds);

            //是生态条线与案件调查报告审批通过插入数据（待分配）
            //String documentCatalogCode1 =  caseDocumentRecords.stream().filter(e-> DocumentStatusEnum.CHECKING.getCode().equals(e.getDocumentApprovalStatus())).collect(Collectors.toList()).get(0).getDocumentCatalogCode();
            if (Constant.ECOLOGICAL_LINE_CODE.equals(caseMainInfo.getCaseTerritoryCode()) && Constant.ECOLOGICAL_INVESTIGATION_REPORT.equals(currentRecordList.get(0).getDocumentId())) {
                caseDistributionRecordService.insertDistribution(caseId);
            }
            if (!isCaseSourceRoll) {
                return result;
            }
            return result1;
        }
        //查询配置表
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(currentRecordList.get(0), "");
        int sortNum = Integer.valueOf(currentRecordList.get(0).getApprovalNum());
        //不是最后一个节点，下一审批人必传
        if (StringUtils.isBlank(approvalAuditDto.getNextHandler()) && caseApprovalFlowRelations.size() > sortNum) {
            throw new BusinessException("系统异常，下一环节处理人必选！");
        }
        // 下一环节待审批信息
        //判断审批记录是否存在
        boolean isExist = checkCaseApprovalWaitRecordIsExist(approvalAuditDto.getCaseId(), currentRecordList.get(0).getDocumentId(), partyId);
        if (isExist) {
            throw new BusinessException("审批通过失败，生成待审批记录已存在，请勿重复提交!");
        }
        CaseApprovalWaitRecord nextRecord = new CaseApprovalWaitRecord();
        BeanUtils.copyProperties(currentRecordList.get(0), nextRecord);
        if (StringUtils.isNotBlank(nextFlow.get(0).getApprovalTerm())) {
            Integer term = nextFlow.get(0).getApprovalTerm().contains("天") ? new Integer(nextFlow.get(0).getApprovalTerm().substring(0, nextFlow.get(0).getApprovalTerm().length() - 1)) : new Integer(nextFlow.get(0).getApprovalTerm());
            nextRecord.setApprovalCurrentLimitTime(term);
            nextRecord.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
        }
        nextRecord.setId(StringUtils.uuid());
        JSONObject baseInfoRequest = new JSONObject();
        if (StringUtils.isBlank(approvalAuditDto.getNextHandler())) {
            CaseMainInfo mainInfo = new CaseMainInfo();
            BeanUtils.copyProperties(caseMainInfo, mainInfo);
            NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(mainInfo, nextFlow.get(0).getApprovalRole(), documentCatalogCode);
            nextRecord.setApprovalUserId(vo.getUserId());
            approvalAuditDto.setNextHandler(vo.getUserId());
            approvalAuditDto.setAutoTime(vo.getAutoTime());
        } else {
            nextRecord.setApprovalUserId(approvalAuditDto.getNextHandler());
        }
        List<String> userIds = new ArrayList<>();
        userIds.addAll(Arrays.asList(approvalAuditDto.getNextHandler().split(",")));
        baseInfoRequest.put("userIds", userIds);
        if (StringUtils.isNotBlank(approvalAuditDto.getApprovalCenterOrgCode())) {
            List<String> orgCodes = new ArrayList<>();
            orgCodes.add(approvalAuditDto.getApprovalCenterOrgCode());
            baseInfoRequest.put("orgCodes", orgCodes);
        }
        //baseInfoRequest.put("orgCodes",approvalAuditDto.getApprovalCenterOrgCode());
        List<ZfPeopleBaseInfoVO> baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userIds", userIds);
        if (null != userIds && userIds.size() > 0) {
            List<String> userNameList = memberUserSignMapper.selectUserNameList(paramMap);
            if (null != userNameList && userNameList.size() > 0) {
                StringJoiner stringJoiner = new StringJoiner(",");
                for (String userName : userNameList) {
                    stringJoiner.add(userName);
                }
                nextRecord.setApprovalUserName(stringJoiner.toString());
            } else {
                nextRecord.setApprovalUserName("");
            }
        } else {
            nextRecord.setApprovalUserName("");
        }
        nextRecord.setApprovalNum(nextFlow.get(0).getApprovalOrderNum());
        nextRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
        nextRecord.setFlowRelationId(nextFlow.get(0).getId());
        if (StringUtils.isNotBlank(approvalAuditDto.getApprovalCenterOrgName())) {
            nextRecord.setApprovalOrgName(approvalAuditDto.getApprovalCenterOrgName());
            if (approvalAuditDto.getApprovalCenterOrgName().contains("联合法制审核")) {
                String approvalCenterOrgName = approvalAuditDto.getApprovalCenterOrgName();
                approvalCenterOrgName = approvalCenterOrgName.substring(approvalCenterOrgName.indexOf("（") + 1, approvalCenterOrgName.indexOf("）"));
                nextRecord.setApprovalOrgName(approvalCenterOrgName);
                nextRecord.setApprovalOrgCode(approvalAuditDto.getApprovalCenterOrgCode());
            }
        } else {
            nextRecord.setApprovalOrgCode(caseMainInfo.getCaseOrgCode());
        }
        nextRecord.setPartyId(partyId);
        nextRecord.setAutoTime(approvalAuditDto.getAutoTime());
        nextRecord.setIsAutoApproval(approvalAuditDto.getIsAutoApproval());
        int nextIn = caseApprovalWaitRecordMapper.insert(nextRecord);
        Boolean f = (del == 1 && completeIn == 1 && nextIn == 1);
        if (f) {
            // 生成审批后文书
            String approvalStatus = DocumentStatusEnum.CHECKING.getCode();
            makeDoc(currentRecordList.get(0).getFlowRelationId(), approvalAuditDto.getCaseId(), currentRecordList.get(0).getDocumentId(), caseDocumentRecords.get(0), approvalAuditDto.getOpinion(), isLast, approvalStatus, partyId, approvalAuditDto.getCaseAssistId(), currentRecordList.get(0).getIsEditApproval(), currentRecordList.get(0).getDocId(), null);
            // 下一审批人,新审批钉钉提醒
            //sendNewAuditDing(approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), nextRecord.getApprovalCurrentLimitTime(), baseInfo);
            sendNewAuditDingMsg(approvalAuditDto.getCaseId(), currentRecordList.get(0).getDocumentId(), nextRecord.getApprovalCurrentLimitTime(), userIds);

            //工作台-消息提醒
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            sendNewAuditPcMsg(caseId, caseMainInfo.getCaseOrgName(), documentCatalogCode, configBusiParamDocumentInfo.getDocumentCatalogName(), nextRecord, caseMainInfo.getCaseOrgCode(), userIds);

            if (!isCaseSourceRoll) {
                result.put("success", "true");
                return result;
            }
            result.put("caseId", approvalAuditDto.getCaseId());
            return result;
        } else {
            throw new BusinessException("审批通过数据处理时出现异常");
        }
    }

    /**
     * 是否展示去设置 1是，0否
     *
     * @param userId
     * @param orgCode
     * @return {@link String}
     * @author liyafeng
     * @date 2023/2/1
     */
    @Override
    public String getApprovalIsShowSetPerson(String userId, String orgCode) {
        String isShow = Constant.STRING_0;
        if (StringUtils.isAnyBlank(userId, orgCode)) {
            return isShow;
        }
        int num = caseApprovalWaitRecordMapper.selectMemberUserRoleNum(userId, orgCode);
        if (num > 0) {
            isShow = Constant.STRING_1;
        }
        return isShow;
    }

    /**
     * 获取当前待审批记录
     *
     * @param approvalAuditDto
     * @return {@link List< CaseApprovalWaitRecord>}
     * @author liyafeng
     * @date 2023/1/4
     */
    private List<CaseApprovalWaitRecord> getCurrentRecordList(ApprovalAgreeAuditDto approvalAuditDto) {
        String partyId = approvalAuditDto.getPartyId();
        Example example = new Example(CaseApprovalWaitRecord.class);
        if (StringUtils.isBlank(partyId)) {
            example.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId());
        } else {
            example.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("partyId", partyId);
        }
        List<CaseApprovalWaitRecord> currentRecordList = caseApprovalWaitRecordMapper.selectByExample(example);
        return currentRecordList;
    }

    /**
     * 保存已完成审批记录
     *
     * @param dto
     * @param caseApprovalWaitRecord
     * @return
     * @author liyafeng
     * @date 2022/12/30
     */
    private void saveCaseApprovalCompleteRecord(ApprovalGeneralSubmitDto dto, CaseApprovalWaitRecord caseApprovalWaitRecord) {
        UserDTO userDTO = UserUtil.getUserInfo();
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        BeanUtils.copyProperties(caseApprovalWaitRecord, caseApprovalCompleteRecord);
        caseApprovalCompleteRecord.setId(StringUtils.uuid());
        caseApprovalCompleteRecord.setApprovalUserId("");
        caseApprovalCompleteRecord.setApprovalNum("0");
        caseApprovalCompleteRecord.setApprovalTime(new Date());
        caseApprovalCompleteRecord.setApprovalOpinion(dto.getOpinion());
        caseApprovalCompleteRecord.setApprovalUserName(null);
        caseApprovalCompleteRecord.setApprovalOrgName(userDTO.getOrgName());
        caseApprovalCompleteRecord.setPartyId(dto.getPartyId());
        int complete = this.caseApprovalCompleteRecordMapper.insert(caseApprovalCompleteRecord);
    }

    /**
     * 保存待审批记录
     *
     * @param dto
     * @return {@link int}
     * @author liyafeng
     * @date 2022/12/30
     */
    private CaseApprovalWaitRecord saveCaseApprovalWaitRecord(ApprovalGeneralSubmitDto dto, CaseMainInfoVo caseMainInfo, ConfigBusiParamDocumentInfo configBusiParamDocumentInfo) {
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(null, dto.getDocumentCatalogCode());
        if (nextFlow == null || nextFlow.size() == 0) {
            throw new BusinessException("未找到下一环节关系数据!");
        }
        // 生成待审批记录
        //判断审批记录是否存在
        boolean isExist = checkCaseApprovalWaitRecordIsExist(dto.getCaseId(), dto.getDocumentCatalogCode(), dto.getPartyId());
        if (isExist) {
            throw new BusinessException("生成待审批记录已存在，请勿重复提交!");
        }
        CaseApprovalWaitRecord caseApprovalWaitRecord = new CaseApprovalWaitRecord();
        caseApprovalWaitRecord.setId(StringUtils.uuid());
        caseApprovalWaitRecord.setApprovalNum(nextFlow.get(0).getApprovalOrderNum());
        caseApprovalWaitRecord.setCaseId(dto.getCaseId());
        caseApprovalWaitRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
        if (StringUtils.isNotBlank(nextFlow.get(0).getApprovalTerm())) {
            Integer term = nextFlow.get(0).getApprovalTerm().contains("天") ? new Integer(nextFlow.get(0).getApprovalTerm().substring(0, nextFlow.get(0).getApprovalTerm().length() - 1)) : new Integer(nextFlow.get(0).getApprovalTerm());
            caseApprovalWaitRecord.setApprovalCurrentLimitTime(term);
            caseApprovalWaitRecord.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
        }
        UserDTO userDTO = UserUtil.getUserInfo();
        caseApprovalWaitRecord.setAddUserId(userDTO.getUserId().toString());
        caseApprovalWaitRecord.setAddUserName(userDTO.getRealName());
        caseApprovalWaitRecord.setDocumentId(dto.getDocumentCatalogCode());
        caseApprovalWaitRecord.setFlowRelationId(nextFlow.get(0).getId());
        //标题：行政处罚的相关审批任务标题为：当事人名称+“的”+文书名称；如“张三的立案审批表”
        //CaseMainInfoVo caseMainInfoVo=caseMainInfoMapper.selectCaseMainInfo(caseId);
        String title = "";
        /*Example examplePd = new Example(ConfigBusiParamDocumentInfo.class);
        examplePd.createCriteria().andEqualTo("documentCatalogCode", documentCatalogCode);
        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoMapper.selectByExample(examplePd);*/
        if (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(caseMainInfo.getCaseStatus()) && ApiVisitDataSourceEnum.PUNISH_AY.getCode().equals(caseMainInfo.getDataSource())) {
            Example example = new Example(CaseSourcePartyInfo.class);
            example.createCriteria().andEqualTo("caseSourceId", caseMainInfo.getId()).andEqualTo("status", Constant.STRING_1);
            List<CaseSourcePartyInfo> caseSourcePartyInfos = caseSourcePartyInfoMapper.selectByExample(example);
            if (caseSourcePartyInfos != null && caseSourcePartyInfos.size() > 0) {
                CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseMainInfo.getId());
                title = caseSourceRegisterMainInfo.getPartyName() + "的" + configBusiParamDocumentInfo.getDocumentKindName();
            } else {
                title = configBusiParamDocumentInfo.getDocumentKindName();
            }
        } else {
            List<CasePartiesRecordVo> partiesRecords = casePartiesRecordService.getCasePartiesInfo(dto.getCaseId());
            CasePartiesRecordVo firstPartyInfo = partiesRecords.get(Constant.INTEGER_0);
            String showPartyName = firstPartyInfo.getPartyName();
            if (partiesRecords.size() == 1) {
                title = showPartyName + "的" + configBusiParamDocumentInfo.getDocumentKindName();
            } else if (partiesRecords.size() > 1) {
                title = showPartyName + "等" + partiesRecords.size() + "个的" + configBusiParamDocumentInfo.getDocumentKindName();
            }
        }
        caseApprovalWaitRecord.setApprovalTitle(title);
        caseApprovalWaitRecord.setAddTime(new Date());
        if (StringUtils.isNotEmpty(dto.getCaseAssistId())) {
            caseApprovalWaitRecord.setCaseAssistId(dto.getCaseAssistId());
        }
        List<ZfPeopleBaseInfoVO> baseInfo = null;
        if (StringUtils.isBlank(dto.getNextHandler())) {
            AuditNextUserQueryDto queryDto = new AuditNextUserQueryDto();
            queryDto.setCaseId(dto.getCaseId());
            queryDto.setDocumentCatalogCode(dto.getDocumentCatalogCode());
            List<NextAuditUserVo> users = getNextNodeUser(queryDto);
            caseApprovalWaitRecord.setApprovalUserId(users.get(0).getUserId());
            caseApprovalWaitRecord.setApprovalUserName(users.get(0).getRealName());
        } else {
            JSONObject baseInfoRequest = new JSONObject();
            List<String> userIds = Arrays.asList(dto.getNextHandler().split(","));
            baseInfoRequest.put("userIds", userIds);
            baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
            caseApprovalWaitRecord.setApprovalUserId(dto.getNextHandler());
            StringJoiner stringJoiner = new StringJoiner(",");
            for (ZfPeopleBaseInfoVO vo : baseInfo) {
                stringJoiner.add(vo.getName());
            }
            caseApprovalWaitRecord.setApprovalOrgName(caseMainInfo.getCaseOrgName());
            caseApprovalWaitRecord.setApprovalUserName(stringJoiner.toString());
            caseApprovalWaitRecord.setApprovalOrgCode(caseMainInfo.getCaseOrgCode());
            caseApprovalWaitRecord.setPartyId(dto.getPartyId());
        }
        caseApprovalWaitRecord.setIsAutoApproval(dto.getIsAutoApproval());
        caseApprovalWaitRecord.setAutoTime(dto.getAutoTime());
        // 生成待审批记录
        int insert = this.caseApprovalWaitRecordMapper.insert(caseApprovalWaitRecord);
        return caseApprovalWaitRecord;
    }

    /**
     * 更新文书记录
     *
     * @param dto
     * @return
     * @author liyafeng
     * @date 2022/12/30
     */
    private CaseDocumentRecord updateDocumentRecord(ApprovalGeneralSubmitDto dto, ConfigBusiParamDocumentInfo configBusiParamDocumentInfo) {
        Example exampleDocRecord = new Example(CaseDocumentRecord.class);
        //特殊处理文书暂停文书,更正公示文书
        if (ObjectUtil.isNotEmpty(configBusiParamDocumentInfo) && CaseStatusChangeTypeEnum.SUSPEND.getDocumentKindCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            CaseMainInfoStatusChangeRecord changeRecord = caseMainInfoStatusChangeRecordService.getCaseMainInfoStatusChangeRecordByChangeType(dto.getCaseId(), CaseStatusChangeTypeEnum.SUSPEND.getCode());
        }
        exampleDocRecord.createCriteria().andEqualTo("id", dto.getDocId()).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        exampleDocRecord.orderBy("documentCreateTime").desc();
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDocRecord);
        if (caseDocumentRecords.isEmpty()) {
            throw new BusinessException("未匹配到文书记录");
        }
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecords.get(0);
        caseDocumentRecord.setDocumentAuditStatus("pending");
        caseDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.CHECKING.getCode());
        // 更新关联文书
        String partyId = dto.getPartyId();
        if (StringUtils.isBlank(partyId)) {
            partyId = caseDocumentRecord.getPartyId();
        }
        updateRelationDocStatus(dto.getDocumentCatalogCode(), "pending", dto.getCaseId(), partyId);
        caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);
        return caseDocumentRecord;
    }


    private int getCompleteInAuto(ApprovalAgreeAuditDto approvalAuditDto, List<CaseApprovalWaitRecord> currentRecord) {
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        BeanUtils.copyProperties(currentRecord.get(0), caseApprovalCompleteRecord);
        caseApprovalCompleteRecord.setId(StringUtils.uuid());
        caseApprovalCompleteRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_AGREE);
        caseApprovalCompleteRecord.setApprovalTime(new Date());
        caseApprovalCompleteRecord.setApprovalUserId(approvalAuditDto.getNowHandler());
        caseApprovalCompleteRecord.setApprovalOpinion(approvalAuditDto.getOpinion());
        caseApprovalCompleteRecord.setFlowRelationId(currentRecord.get(0).getFlowRelationId());
        caseApprovalCompleteRecord.setApprovalUserName(currentRecord.get(0).getApprovalUserName());
        caseApprovalCompleteRecord.setApprovalOrgName(currentRecord.get(0).getApprovalOrgName());
        caseApprovalCompleteRecord.setApprovalOrgCode(currentRecord.get(0).getApprovalOrgCode());
        int completeIn = caseApprovalCompleteRecordMapper.insert(caseApprovalCompleteRecord);
        return completeIn;
    }

    private Map<String, Object> finalNodeProcessAuto(ApprovalAgreeAuditDto approvalAuditDto, List<CaseApprovalWaitRecord> currentRecord, int del, int completeIn, List<CaseApprovalFlowRelation> caseApprovalFlowRelations, Map<String, Object> result, List<CaseDocumentRecord> caseDocumentRecords, String partyId, String caseAssistId) {
        if (Integer.valueOf(currentRecord.get(0).getApprovalNum()) == caseApprovalFlowRelations.size()) {
            // 只需要存入审批完成，删除待审批记录
            if (del == 1 && completeIn == 1) {
                //文书状态更改
                if (caseDocumentRecords.isEmpty()) {
                    throw new BusinessException("最后审批节点处理传入文书记录为空");
                }
                caseDocumentRecords = caseDocumentRecords.stream().filter(e -> DocumentStatusEnum.CHECKING.getCode().equals(e.getDocumentApprovalStatus())).collect(Collectors.toList());
                CaseDocumentRecord caseDocumentRecordForUpdate = caseDocumentRecords.get(0);
                caseDocumentRecordForUpdate.setDocumentAuditStatus("pass");
                caseDocumentRecordForUpdate.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_END.getCode());
                caseDocumentRecordForUpdate.setDocumentApprovalTime(LocalDateTime.now());
                //判断是否需要更新案件状态，查询配置表
                if (caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecordForUpdate) == 1) {
                    // 更新关联文书
                    updateRelationDocStatus(caseDocumentRecordForUpdate.getDocumentCatalogCode(), "pass", approvalAuditDto.getCaseId(), partyId);
                    result.put("caseId", approvalAuditDto.getCaseId());
                    // 生成审批完成文书
                    invokeDocAuto(approvalAuditDto, currentRecord, caseDocumentRecords, partyId, caseAssistId);
                    updateMain(approvalAuditDto, currentRecord);
                    //保存案源审批通过流转日志
                    CaseMainInfoVo caseMainInfo = caseMainInfoMapper.selectCaseMainInfo(approvalAuditDto.getCaseId());
                    boolean isSaveCaseSourceFolw = getIsSaveCaseSourceFolwLog(caseMainInfo, currentRecord.get(0).getDocumentId());
                    if (isSaveCaseSourceFolw) {
                        saveCaseSourceApprovalFlow(caseMainInfo);
                    }
                    result.put("closeSignal", "CLOSE-TRIGGER-APPROVAL-PASS");
                    return result;
                } else {
                    throw new BusinessException("更新文书记录信息时出现异常");
                }
            } else {
                throw new BusinessException("最后审批节点数据处理时出现异常");
            }
        }
        return null;
    }


    /**
     * 描述: 向大综合推送浙里办站内消息
     *
     * @return void
     * @author zhanghongqiang
     * @Date 2022/12/9
     */
    public void comprehensiveMsg(PunishMsgParams punishMsgParams) {
        log.info("开始推送消息到大综合-------------");
        try {
            String paramStr = JSON.toJSONString(punishMsgParams);
            log.info("comprehensiveMsg -- 入参: {}", paramStr);
            String response = HttpUtil.createPost(taskCenterUrl.concat(saveEntMessage)).body(paramStr).execute().body();
            log.info("comprehensiveMsg -- 出参: {}", response);
            Result result = JSONObject.parseObject(response, Result.class);
            String resultJson = JSON.toJSONString(result);
            log.info("comprehensiveMsg -- 结果: {}", resultJson);

        } catch (JSONException e) {
            log.warn("json格式错误");
        } catch (Exception e) {
            log.error("comprehensiveMsg:", e);
        }
    }

    /**
     * 最后审批节点处理
     *
     * @param approvalAuditDto
     * @param currentRecord
     * @param del
     * @param completeIn
     * @param caseApprovalFlowRelations
     * @param result
     * @param caseDocumentRecords
     * @return
     */
    private Map<String, Object> finalNodeProcess(ApprovalAgreeAuditDto approvalAuditDto, List<CaseApprovalWaitRecord> currentRecord, int del, int completeIn, List<CaseApprovalFlowRelation> caseApprovalFlowRelations, Map<String, Object> result, List<CaseDocumentRecord> caseDocumentRecords, String partyId, String caseAssistId) {
        if (Integer.valueOf(currentRecord.get(0).getApprovalNum()) == caseApprovalFlowRelations.size()) {
            // 只需要存入审批完成，删除待审批记录
            if (del == 1 && completeIn == 1) {
                //文书状态更改
                if (caseDocumentRecords.isEmpty()) {
                    throw new BusinessException("最后审批节点处理传入文书记录为空");
                }
                caseDocumentRecords = caseDocumentRecords.stream().filter(e -> DocumentStatusEnum.CHECKING.getCode().equals(e.getDocumentApprovalStatus())).collect(Collectors.toList());
                CaseDocumentRecord caseDocumentRecordForUpdate = caseDocumentRecords.get(0);
                caseDocumentRecordForUpdate.setDocumentAuditStatus("pass");
                caseDocumentRecordForUpdate.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_END.getCode());
                caseDocumentRecordForUpdate.setDocumentApprovalTime(LocalDateTime.now());
                //判断是否需要更新案件状态，查询配置表
                if (caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecordForUpdate) == 1) {
                    // 更新关联文书
                    updateRelationDocStatusByApprovalDocumentId(caseDocumentRecordForUpdate.getDocumentCatalogCode(), "pass", approvalAuditDto.getCaseId(), partyId, caseDocumentRecordForUpdate.getId());
                    result.put("caseId", approvalAuditDto.getCaseId());
                    // 生成审批完成文书
                    invokeDoc(approvalAuditDto, currentRecord, caseDocumentRecords, partyId, caseAssistId);
                    if (Constant.STRING_1.equals(currentRecord.get(0).getIsEditApproval())) {
                        caseDocumentRecordService.modifyDocumentRecordAfterApproval(currentRecord.get(0).getDocId());
                    }
                    String isEditApproval = currentRecord.get(0).getIsEditApproval();
                    if (!Constant.STRING_1.equals(isEditApproval)) {
                        updateMain(approvalAuditDto, currentRecord);
                    }
                    //保存案源审批通过流转日志
                    CaseMainInfoVo caseMainInfo = caseMainInfoMapper.selectCaseMainInfo(approvalAuditDto.getCaseId());
                    boolean isSaveCaseSourceFolw = getIsSaveCaseSourceFolwLog(caseMainInfo, currentRecord.get(0).getDocumentId());
                    if (isSaveCaseSourceFolw) {
                        saveCaseSourceApprovalFlow(caseMainInfo);
                    }

                    return result;
                } else {
                    throw new BusinessException("更新文书记录信息时出现异常");
                }
            } else {
                throw new BusinessException("最后审批节点数据处理时出现异常");
            }
        }
        return null;
    }

    /**
     * 最后审批节点处理
     *
     * @param approvalAuditDto
     * @param currentRecord
     * @param del
     * @param completeIn
     * @param caseApprovalFlowRelations
     * @param result
     * @param executeDocumentRecords
     * @return
     */
    private Map<String, Object> finalNodeProcessWithExecute(ApprovalAgreeAuditDto approvalAuditDto, List<CaseApprovalWaitRecord> currentRecord, int del, int completeIn, List<CaseApprovalFlowRelation> caseApprovalFlowRelations, Map<String, Object> result, List<ExecuteDocumentRecord> executeDocumentRecords, String partyId) {
        if (Integer.valueOf(currentRecord.get(0).getApprovalNum()) == caseApprovalFlowRelations.size()) {
            // 只需要存入审批完成，删除待审批记录
            if (del == 1 && completeIn == 1) {
                //文书状态更改
                if (executeDocumentRecords.isEmpty()) {
                    throw new BusinessException("最后审批节点处理传入文书记录为空");
                }
                executeDocumentRecords = executeDocumentRecords.stream().filter(e -> DocumentStatusEnum.CHECKING.getCode().equals(e.getDocumentApprovalStatus())).collect(Collectors.toList());
                ExecuteDocumentRecord executeDocumentRecordForUpdate = executeDocumentRecords.get(0);
                executeDocumentRecordForUpdate.setDocumentAuditStatus("pass");
                executeDocumentRecordForUpdate.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_END.getCode());
                executeDocumentRecordForUpdate.setDocumentApprovalTime(new Date());
                //判断是否需要更新案件状态，查询配置表
                if (executeDocumentRecordMapper.updateByPrimaryKeySelective(executeDocumentRecordForUpdate) == 1) {
                    // 更新关联文书
                    updateRelationDocStatus(executeDocumentRecordForUpdate.getDocumentCatalogCode(), "pass", approvalAuditDto.getCaseId(), partyId);
                    result.put("caseId", approvalAuditDto.getCaseId());
                    // 生成审批完成文书
                    invokeExecuteDoc(approvalAuditDto, currentRecord, executeDocumentRecords, partyId);
                    updateExecuteMainMain(approvalAuditDto, currentRecord);
                    //保存案源审批通过流转日志
                    ExecuteMainInfo executeMainInfo = executeMainInfoService.getByExecuteId(approvalAuditDto.getCaseId());

                    boolean isSaveExecuteFolw = getIsSaveExecuteFolwLog(currentRecord.get(0).getDocumentId());
                    if (isSaveExecuteFolw) {
                        //saveExecuteApprovalFlow(executeMainInfo);
                    }
                    return result;
                } else {
                    throw new BusinessException("更新文书记录信息时出现异常");
                }
            } else {
                throw new BusinessException("最后审批节点数据处理时出现异常");
            }
        }
        return null;
    }

    /**
     * 保存案源审批通过流转日志
     *
     * @param
     * @return
     * @author liyafeng
     * @date 2022/8/18
     */
    private void saveCaseSourceApprovalFlow(CaseMainInfoVo caseMainInfo) {
        CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseMainInfo.getId());
        FlowCommonDto flowCommonDto = new FlowCommonDto();
        UserDTO userDTO = UserUtil.getUserInfo();
        flowCommonDto.setCaseSourceId(caseSourceRegisterMainInfo.getId());
        flowCommonDto.setStartPersonName(userDTO.getRealName());
        flowCommonDto.setStartPersonOrgName(userDTO.getOrgName());
        flowCommonDto.setFlowStartTime(new Date());
        flowCommonDto.setFlowEndTime(new Date());
        flowCommonDto.setStartPersonDeptName(userDTO.getDeptName());
        flowCommonDto.setFlowStageType(Constant.CASE_SOURCE_STAGE_LASPTG);
        if (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(caseMainInfo.getCaseStatus())) {
            flowCommonDto.setFlowStageType(Constant.CASE_SOURCE_STAGE_BYLASPTG);
        }
        caseSourceFlowRecordService.saveCommonFlowRecord(flowCommonDto);
        //更新案源状态
        CaseSourceRegisterMainInfo updateCaseSourceRegisterMainInfo = new CaseSourceRegisterMainInfo();
        updateCaseSourceRegisterMainInfo.setId(caseSourceRegisterMainInfo.getId());
        updateCaseSourceRegisterMainInfo.setCaseSourceStatus(CaseSourceStatusEnum.REGISTERED.getIndex());
        updateCaseSourceRegisterMainInfo.setCaseSourceStageCode(Constant.CASE_SOURCE_STAGE_LASPTG);
        if (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(caseMainInfo.getCaseStatus())) {
            updateCaseSourceRegisterMainInfo.setCaseSourceStatus(CaseSourceStatusEnum.NO_REGISTERED.getIndex());
            updateCaseSourceRegisterMainInfo.setCaseSourceStageCode(Constant.CASE_SOURCE_STAGE_BYLASPTG);
        }
        caseSourceRegisterMainInfoMapper.updateByPrimaryKeySelective(updateCaseSourceRegisterMainInfo);
        //todo
        //立案时将证据材料代入调查阶段
    }

    /**
     * 保存案源审批通过流转日志
     *
     * @param
     * @return
     * @author liyafeng
     * @date 2022/8/18
     */
    private void saveExecuteApprovalFlow(ExecuteMainInfo executeMainInfo) {
        //CaseSourceRegisterMainInfo caseSourceRegisterMainInfo=caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseMainInfo.getId());
        ExecuteFlowCommonDto flowCommonDto = new ExecuteFlowCommonDto();
        UserDTO userDTO = UserUtil.getUserInfo();
        flowCommonDto.setExecuteId(executeMainInfo.getExecuteId());
        flowCommonDto.setStartPersonName(userDTO.getRealName());
        flowCommonDto.setStartPersonOrgName(userDTO.getOrgName());
        flowCommonDto.setFlowStartTime(new Date());
        flowCommonDto.setFlowEndTime(new Date());
        flowCommonDto.setStartPersonDeptName(userDTO.getDeptName());
        flowCommonDto.setFlowStageType(Constant.CASE_SOURCE_STAGE_LASPTG);
        if (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(executeMainInfo.getCaseStatus())) {
            flowCommonDto.setFlowStageType(Constant.CASE_SOURCE_STAGE_BYLASPTG);
        }
        executeFlowRecordService.saveCommonFlowRecord(flowCommonDto);
        //更新裁执分离状态
        CaseSourceRegisterMainInfo updateCaseSourceRegisterMainInfo = new CaseSourceRegisterMainInfo();
        updateCaseSourceRegisterMainInfo.setId(executeMainInfo.getId());
        updateCaseSourceRegisterMainInfo.setCaseSourceStatus(CaseSourceStatusEnum.REGISTERED.getIndex());
        updateCaseSourceRegisterMainInfo.setCaseSourceStageCode(Constant.CASE_SOURCE_STAGE_LASPTG);
        if (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(executeMainInfo.getCaseStatus())) {
            updateCaseSourceRegisterMainInfo.setCaseSourceStatus(CaseSourceStatusEnum.NO_REGISTERED.getIndex());
            updateCaseSourceRegisterMainInfo.setCaseSourceStageCode(Constant.CASE_SOURCE_STAGE_BYLASPTG);
        }
        caseSourceRegisterMainInfoMapper.updateByPrimaryKeySelective(updateCaseSourceRegisterMainInfo);
        //todo
        //立案时将证据材料代入调查阶段
    }

    /**
     * 已审批保存
     *
     * @param approvalAuditDto
     * @param currentRecord
     * @return
     */
    private int getCompleteIn(ApprovalAgreeAuditDto approvalAuditDto, List<CaseApprovalWaitRecord> currentRecord) {
        UserDTO userDTO = UserUtil.getUserInfo();
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        BeanUtils.copyProperties(currentRecord.get(0), caseApprovalCompleteRecord);
        caseApprovalCompleteRecord.setId(StringUtils.uuid());
        caseApprovalCompleteRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_AGREE);
        caseApprovalCompleteRecord.setApprovalTime(new Date());
        caseApprovalCompleteRecord.setApprovalUserId(userDTO.getUserId().toString());
        caseApprovalCompleteRecord.setApprovalOpinion(approvalAuditDto.getOpinion());
        caseApprovalCompleteRecord.setFlowRelationId(currentRecord.get(0).getFlowRelationId());
        caseApprovalCompleteRecord.setApprovalUserName(userDTO.getRealName());
        caseApprovalCompleteRecord.setApprovalOrgName(currentRecord.get(0).getApprovalOrgName());
        caseApprovalCompleteRecord.setApprovalOrgCode(currentRecord.get(0).getApprovalOrgCode());
        int completeIn = caseApprovalCompleteRecordMapper.insert(caseApprovalCompleteRecord);
        return completeIn;
    }

    /**
     * 已审批保存
     *
     * @param approvalAuditDto
     * @param userDTO
     * @param currentRecord
     * @return
     */
    private int getCompleteInExecute(ApprovalAgreeAuditDto approvalAuditDto, UserDTO userDTO, List<CaseApprovalWaitRecord> currentRecord) {
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        BeanUtils.copyProperties(currentRecord.get(0), caseApprovalCompleteRecord);
        caseApprovalCompleteRecord.setId(StringUtils.uuid());
        caseApprovalCompleteRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_AGREE);
        caseApprovalCompleteRecord.setApprovalTime(new Date());
        caseApprovalCompleteRecord.setApprovalUserId(userDTO.getUserId().toString());
        caseApprovalCompleteRecord.setApprovalOpinion(approvalAuditDto.getOpinion());
        caseApprovalCompleteRecord.setFlowRelationId(currentRecord.get(0).getFlowRelationId());
        caseApprovalCompleteRecord.setApprovalUserName(userDTO.getRealName());
        caseApprovalCompleteRecord.setApprovalOrgName(userDTO.getOrgName());
        caseApprovalCompleteRecord.setApprovalOrgCode(userDTO.getOrgCode());
        caseApprovalCompleteRecord.setApprovalType("2");
        int completeIn = caseApprovalCompleteRecordMapper.insert(caseApprovalCompleteRecord);
        return completeIn;
    }

    /**
     * 生成审批完成文书
     *
     * @param approvalAuditDto
     * @param currentRecord
     * @param caseDocumentRecords
     */
    private void invokeDoc(ApprovalAgreeAuditDto approvalAuditDto, List<CaseApprovalWaitRecord> currentRecord, List<CaseDocumentRecord> caseDocumentRecords, String partyId, String caseAssistId) {
        boolean isLast;
        isLast = true;
        String approvalStatus = DocumentStatusEnum.CHECK_END.getCode();
        Map<String, Object> resultMap = makeDoc(currentRecord.get(0).getFlowRelationId(), approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), caseDocumentRecords.get(0), approvalAuditDto.getOpinion(), isLast, approvalStatus, partyId, caseAssistId, currentRecord.get(0).getIsEditApproval(), currentRecord.get(0).getDocId(), approvalAuditDto.getExceptionCaseDocumentSerialKey());
        String status = MapUtils.getString(resultMap, "success", "");
        String tr = "true";
        if (!tr.equals(status)) {
            throw new BusinessException("文书生成失败！");
        }
    }

    /**
     * 生成审批完成文书
     *
     * @param approvalAuditDto
     * @param currentRecord
     * @param caseDocumentRecords
     */
    private void invokeDocAuto(ApprovalAgreeAuditDto approvalAuditDto, List<CaseApprovalWaitRecord> currentRecord, List<CaseDocumentRecord> caseDocumentRecords, String partyId, String caseAssistId) {
        boolean isLast;
        isLast = true;
        String approvalStatus = DocumentStatusEnum.CHECK_END.getCode();
        Map<String, Object> resultMap = makeDocAuto(currentRecord.get(0).getFlowRelationId(), approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), caseDocumentRecords.get(0), approvalAuditDto.getOpinion(), isLast, approvalStatus, partyId, caseAssistId, approvalAuditDto.getNowHandler());
        String status = MapUtils.getString(resultMap, "success", "");
        String tr = "true";
        if (!tr.equals(status)) {
            throw new BusinessException("文书生成失败！");
        }
    }

    /**
     * 生成审批完成文书
     *
     * @param approvalAuditDto
     * @param currentRecord
     * @param executeDocumentRecords
     */
    private void invokeExecuteDoc(ApprovalAgreeAuditDto approvalAuditDto, List<CaseApprovalWaitRecord> currentRecord, List<ExecuteDocumentRecord> executeDocumentRecords, String partyId) {
        boolean isLast;
        isLast = true;
        String approvalStatus = DocumentStatusEnum.CHECK_END.getCode();
        Map<String, Object> resultMap = makeExecuteDoc(currentRecord.get(0).getFlowRelationId(), approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), executeDocumentRecords.get(0), approvalAuditDto.getOpinion(), isLast, approvalStatus, partyId);
        String status = MapUtils.getString(resultMap, "success", "");
        String tr = "true";
        if (!tr.equals(status)) {
            throw new BusinessException("文书生成失败！");
        }
    }

    /**
     * 更新关联文书状态
     *
     * @param docId
     * @param approvalStatus
     */
    private void updateRelationDocStatus(String docId, String approvalStatus, String caseId, String partyId) {
        // 查询关联文书
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(docId);
        if (StringUtils.isNotBlank(configBusiParamDocumentInfo.getRelationDocumentCatalogCode())) {
            String fg = ",";
            String[] relationDocs = configBusiParamDocumentInfo.getRelationDocumentCatalogCode().split(fg);
            CaseDocumentRecord param = new CaseDocumentRecord();
            for (int i = 0; i < relationDocs.length; i++) {
                Example example = new Example(CaseDocumentRecord.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", relationDocs[i]).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode()).andNotEqualTo("documentApprovalStatus", DocumentStatusEnum.CHECK_END.getCode());
                if (StringUtils.isNotBlank(partyId)) {
                    criteria.andEqualTo("partyId", partyId);
                }
                List<CaseDocumentRecord> updateRecord = caseDocumentRecordMapper.selectByExample(example);

                if (!updateRecord.isEmpty()) {
                    CaseDocumentRecord record = updateRecord.get(0);
                    record.setDocumentAuditStatus(approvalStatus);
                    String pass = "pass";
                    String pending = "pending";
                    String rt = "return";
                    // 状态判断更新
                    if (pass.equals(approvalStatus)) {
                        record.setDocumentApprovalTime(LocalDateTime.now());
                        record.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_END.getCode());
                    }
                    if (pending.equals(approvalStatus)) {
                        record.setDocumentApprovalStatus(DocumentStatusEnum.CHECKING.getCode());
                    }
                    if (rt.equals(approvalStatus)) {
                        record.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_BACK.getCode());
                    }
                    caseDocumentRecordMapper.updateByPrimaryKeySelective(record);
                }
            }
        }
    }

    /**
     * 更新关联文书状态
     *
     * @param docId
     * @param approvalStatus
     */
    private void updateRelationExecuteDocStatus(String docId, String approvalStatus, String caseId, String partyId) {
        // 查询关联文书
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(docId);
        if (StringUtils.isNotBlank(configBusiParamDocumentInfo.getRelationDocumentCatalogCode())) {
            String fg = ",";
            String[] relationDocs = configBusiParamDocumentInfo.getRelationDocumentCatalogCode().split(fg);
            ExecuteDocumentRecord param = new ExecuteDocumentRecord();
            for (int i = 0; i < relationDocs.length; i++) {
                Example example = new Example(ExecuteDocumentRecord.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("executeId", caseId).andEqualTo("documentCatalogCode", relationDocs[i]).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode()).andNotEqualTo("documentApprovalStatus", DocumentStatusEnum.CHECK_END.getCode());
                if (StringUtils.isNotBlank(partyId)) {
                    criteria.andEqualTo("partyId", partyId);
                }
                List<ExecuteDocumentRecord> updateRecord = executeDocumentRecordMapper.selectByExample(example);

                if (!updateRecord.isEmpty()) {
                    ExecuteDocumentRecord record = updateRecord.get(0);
                    record.setDocumentAuditStatus(approvalStatus);
                    String pass = "pass";
                    String pending = "pending";
                    String rt = "return";
                    // 状态判断更新
                    if (pass.equals(approvalStatus)) {
                        record.setDocumentApprovalTime(new Date());
                        record.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_END.getCode());
                    }
                    if (pending.equals(approvalStatus)) {
                        record.setDocumentApprovalStatus(DocumentStatusEnum.CHECKING.getCode());
                    }
                    if (rt.equals(approvalStatus)) {
                        record.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_BACK.getCode());
                    }
                    executeDocumentRecordMapper.updateByPrimaryKeySelective(record);
                }
            }
        }
    }

    /**
     * 更新裁执分离主表数据
     *
     * @param approvalAuditDto
     * @param currentRecord
     */
    private void updateExecuteMainMain(ApprovalAgreeAuditDto approvalAuditDto, List<CaseApprovalWaitRecord> currentRecord) {
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(currentRecord.get(0).getDocumentId());
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        //执行回执
        String zxhz = "ZXHZ";
        if (zxhz.equals(documentKindCode)) {
            ExecuteMainInfo executeMainInfo = executeMainInfoService.getByExecuteId(approvalAuditDto.getCaseId());
            executeMainInfo.setCaseStatus("3");
            Example executeMainInfoUpdateExample = new Example(ExecuteMainInfo.class);
            executeMainInfoUpdateExample.createCriteria().andEqualTo("executeId", executeMainInfo.getExecuteId());
            executeMainInfoMapper.updateByExample(executeMainInfo, executeMainInfoUpdateExample);
            //执行回执审批完成，回调法院接口
            ExecuteDataRequestDto request = new ExecuteDataRequestDto();
            request.setExecuteId(executeMainInfo.getExecuteId());
            request.setRuleNumber(request.getRuleNumber());
            String pattern = "yyyy-MM-dd";
            //执行日期
            request.setExecuteDate(DateFormatUtils.format(executeMainInfo.getCloseCaseTime(), pattern));
            //执行结果-使用结案情况说明字段
            request.setExecuteConclusion(executeMainInfo.getCloseCaseDesc());
            //执行周期  示例 “立案日期 XXXX-XX-XX 结案日期 XXXX-XX-XX 总计 X 天”
            request.setExecuteCycle("立案日期 " + executeMainInfo.getAcceptanceTime().format(DateTimeFormatter.ofPattern(pattern)) + " 结案日期 " + DateFormatUtils.format(executeMainInfo.getCloseCaseTime(), pattern) + " 总计 " + BaseUtil.getBetweenDays(DateUtil.localDateTimeToDate(executeMainInfo.getAcceptanceTime()), executeMainInfo.getCloseCaseTime()) + " 天");
            //执行人员
            request.setExecutePerson(executeMainInfo.getHandlePersonMainName() + "," + executeMainInfo.getHandlePersonAssistName());
            //执行机构
            request.setExecuteOfficeName(executeMainInfo.getExecuteOrgName());
            executeMainInfoService.closingCallback(request);
        }
    }

    /**
     * 更新案件主表数据
     *
     * @param approvalAuditDto
     * @param currentRecord
     */
    private void updateMain(ApprovalAgreeAuditDto approvalAuditDto, List<CaseApprovalWaitRecord> currentRecord) {
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(currentRecord.get(0).getDocumentId());
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(approvalAuditDto.getCaseId());
        String laspb = "LASPB";
        if (laspb.equals(documentKindCode)) {
            CaseMainInfo updateCaseMainInfo = new CaseMainInfo();
            updateCaseMainInfo.setId(approvalAuditDto.getCaseId());
            updateCaseMainInfo.setCaseRegistTime(LocalDateTime.now());
            //应急办案期限是30天，其他是90天
            if (TerritoryCodeEnum.YJGL.getCode().equals(caseMainInfo.getCaseTerritoryCode())) {
                updateCaseMainInfo.setCaseTimelimit(LocalDateTime.now().plusDays(30));
                updateCaseMainInfo.setCaseDeadline(30);
            } else {
                // 截止时间目前写死，后面读取配置
                updateCaseMainInfo.setCaseTimelimit(LocalDateTime.now().plusDays(90));
                updateCaseMainInfo.setCaseDeadline(90);
            }
            caseMainInfoMapper.updateByPrimaryKeySelective(updateCaseMainInfo);
            CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
            updateCaseMainDetailInfo.setCaseId(approvalAuditDto.getCaseId());
            updateCaseMainDetailInfo.setCaseRegisterTime(DateUtils.formatDate(new Date(), "yyyy年MM月dd日"));
            caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);

            //检查转处罚案件,调用处罚结果回传
            caseRegisterService.sendDisposalBackResult(approvalAuditDto.getCaseId());
        } else if (DocumentKindEnum.DOC_KIND_DK1SXFZAJYSSPB.getCode().equals(documentKindCode)) {
            //涉嫌犯罪案件移送书审批通过后
            //1.系统自动推送涉刑移送案件信息至两法衔接平台
            //2.案件状态变更为“已中止”
            CaseBaseInfoResponse caseBaseInfoResponse = caseTransferApiService.getTransferDetailAfterApproval(approvalAuditDto.getCaseId());
            Result result = lawenforceBusinessService.sendTransferDataByCaseBaseInfo(caseBaseInfoResponse);
            if (HttpStatus.HTTP_OK == result.getCode()) {
                //移送成功
                EditCaseStatusDto editCaseStatusDto = new EditCaseStatusDto();
                editCaseStatusDto.setCaseId(approvalAuditDto.getCaseId());
                //更新案件状态为中止
                editCaseStatusDto.setCaseChangeStatus(Constant.STRING_1);
                lawJoinService.editCaseStatusByLawJoinCallBack(editCaseStatusDto);
            }

        } else if (DocumentKindEnum.DOC_KIND_DK1BYLASPB.getCode().equals(documentKindCode) &&
                StrUtil.isNotEmpty(caseMainInfo.getLineCode()) && caseMainInfo.getLineCode().contains(TerritoryCodeEnum.RLSB.getCode())) {
            CollectReportDataDto dto = new CollectReportDataDto();
            dto.setCaseId(caseMainInfo.getId());
            dto.setCaseTerritoryCode(TerritoryCodeEnum.RLSB.getCode());
            dto.setCasePartyType("1");
            dataReportService.caseDataReport(dto);
        }
        //如果是撤销立案审批表，生成一条记录，然后定时重新上报已经上报成功的数据
        if (DocumentKindEnum.DOC_KIND_CXLASQB.getCode().equals(documentKindCode)) {
            String userId = "";
            UserDTO userInfo = UserUtil.getUserInfo();
            if (userInfo != null) {
                userId = String.valueOf(userInfo.getUserId());
            }
            caseDataChangeReportRecordService.save(approvalAuditDto.getCaseId(), CaseChangeOperationTypeEnum.OPERATION_TYPE_6.getCode(), userId);
        }
        CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
        updateCaseMainDetailInfo.setCaseId(approvalAuditDto.getCaseId());
        updateCaseMainDetailInfo.setSimpleFormType("-1");
        caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);
    }

    @Override
    @WorkFlowRollAnnotation
    public Map<String, Object> doReturnAudit(ApprovalReturnlAuditDto approvalAuditDto) {
        CaseMainInfoVo caseMainInfo = caseMainInfoMapper.selectCaseMainInfo(approvalAuditDto.getCaseId());
        String handleType = caseMainInfo.getHandleType();
        //读取当前用户，当前审批环节，校验角色权限，根据审批结果，流转下个节点
        // 校验审批权限 （不做了，能查到，数据存入时已校验处理）
        // 审批结果写入 case_approval_complete_record 已完成审批表 ，
        // 审批通过 写入下个节点  写入 待审批 case_approval_wait_record
        UserDTO userDTO = UserUtil.getUserInfo();
        String docId = approvalAuditDto.getDocId();
        List<CaseApprovalWaitRecord> currentRecord = null;
        List<CaseDocumentRecord> caseDocumentRecords = null;
        if (StringUtils.isNotBlank(docId)) {
            Example waitExample = new Example(CaseApprovalWaitRecord.class);
            waitExample.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("docId", docId);
            currentRecord = caseApprovalWaitRecordMapper.selectByExample(waitExample);
            Example docRecordExample = new Example(CaseDocumentRecord.class);
            docRecordExample.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("id", docId).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId()).andNotEqualTo("documentApprovalStatus", DocumentStatusEnum.CHECK_END.getCode());
            caseDocumentRecords = caseDocumentRecordMapper.selectByExample(docRecordExample);
            if (Constant.STRING_1.equals(caseDocumentRecords.get(0).getIsModifyRecord())) {
                //如果是变更文书,走修改文书审批
                return doReturnAuditOfModifyDocument(approvalAuditDto);
            }
        }
        if (org.springframework.util.ObjectUtils.isEmpty(currentRecord)) {
            //删除当前节点
            Example example = new Example(CaseApprovalWaitRecord.class);
            if (StringUtils.isBlank(approvalAuditDto.getPartyId())) {
                example.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentId", approvalAuditDto.getDocumentCatalogCode());
            } else {
                example.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("partyId", approvalAuditDto.getPartyId()).andEqualTo("documentId", approvalAuditDto.getDocumentCatalogCode());
            }
            currentRecord = caseApprovalWaitRecordMapper.selectByExample(example);
        }
        if (currentRecord.isEmpty()) {
            throw new BusinessException("当前无审批任务");
        }
        //判断是否需要滚流程
        boolean isCaseSourceRoll = getIsCaseSourceRoll(caseMainInfo, currentRecord.get(0).getDocumentId());
       /* if(isSaveCaseSourceFlow){
            CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseMainInfo.getId());
            saveCaseSourceFlow(caseSourceRegisterMainInfo, caseMainInfo);
        }*/
        // 退回节点 上一节点，发起人
        //退回到发起人操作
        String start = "start";
        String one = "1";
        Map<String, Object> result = new HashMap<>(8);
        // 分布式锁
        if (org.springframework.util.ObjectUtils.isEmpty(caseDocumentRecords)) {
            docId = currentRecord.get(0).getDocId();
            Example exampleDocRecord = new Example(CaseDocumentRecord.class);
            if (StringUtils.isNotBlank(docId)) {
                exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId()).andEqualTo("id", docId).andNotEqualTo("documentApprovalStatus", DocumentStatusEnum.CHECK_END.getCode());
            } else {
                if (StringUtils.isBlank(approvalAuditDto.getPartyId())) {
                    exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId()).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode()).andNotEqualTo("documentApprovalStatus", DocumentStatusEnum.CHECK_END.getCode());
                } else {
                    exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId()).andEqualTo("partyId", approvalAuditDto.getPartyId()).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode()).andNotEqualTo("documentApprovalStatus", DocumentStatusEnum.CHECK_END.getCode());
                }
            }
            caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDocRecord);
            if (Constant.STRING_1.equals(caseDocumentRecords.get(0).getIsModifyRecord())) {
                //如果是变更文书,走修改文书审批
                approvalAuditDto.setDocId(caseDocumentRecords.get(0).getId());
                return doReturnAuditOfModifyDocument(approvalAuditDto);
            }
        }
        //删除待审批节点
        //已审批通过记录保存
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        BeanUtils.copyProperties(currentRecord.get(0), caseApprovalCompleteRecord);
        caseApprovalCompleteRecord.setId(StringUtils.uuid());
        caseApprovalCompleteRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_RETURN);
        caseApprovalCompleteRecord.setApprovalTime(new Date());
        caseApprovalCompleteRecord.setApprovalUserId(userDTO.getUserId().toString());
        caseApprovalCompleteRecord.setApprovalOpinion(approvalAuditDto.getOpinion());
        caseApprovalCompleteRecord.setApprovalUserName(userDTO.getRealName());
        caseApprovalCompleteRecord.setApprovalBackType(approvalAuditDto.getReturnNode());
        caseApprovalCompleteRecord.setApprovalOrgName(userDTO.getOrgName());
        caseApprovalCompleteRecord.setApprovalOrgCode(userDTO.getOrgCode());
        int completeIn = caseApprovalCompleteRecordMapper.insert(caseApprovalCompleteRecord);
        int del = caseApprovalWaitRecordMapper.deleteByPrimaryKey(currentRecord.get(0).getId());
        // 判断退回上一步是否发起人或退回环节为发起人
        if (start.equals(approvalAuditDto.getReturnNode()) || one.equals(currentRecord.get(0).getApprovalNum())) {
            //案源来源审批数据 提交审批完成后 新增流转日志
            //判断是否需要保存日志
            boolean isSaveCaseSourceFlow = getIsSaveCaseSourceFolwLog(caseMainInfo, currentRecord.get(0).getDocumentId());
            if (isSaveCaseSourceFlow) {
                CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(approvalAuditDto.getCaseId());
                rmCaseSourceFlow(caseSourceRegisterMainInfo, caseMainInfo);
                //重置案源为指派状态
                caseSourceRegisterMainInfo.setCaseSourceStageCode(Constant.CASE_SOURCE_STAGE_AYZP);
                caseSourceRegisterMainInfoMapper.updateByPrimaryKeySelective(caseSourceRegisterMainInfo);

            }
            // 文书状态改为未提交:修改文书表状态
            if (caseDocumentRecords.isEmpty()) {
                throw new BusinessException("未匹配到文书记录-doReturnAudit");
            }
            CaseDocumentRecord caseDocumentRecordForUpdate = caseDocumentRecords.get(0);
            caseDocumentRecordForUpdate.setDocumentAuditStatus("return");
            caseDocumentRecordForUpdate.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_BACK.getCode());
            // 清空审批意见
            clearOpinion(caseDocumentRecordForUpdate);
            // 更新关联文书
            //updateRelationDocStatus(caseDocumentRecordForUpdate.getDocumentCatalogCode(),"return",approvalAuditDto.getCaseId(),approvalAuditDto.getPartyId());
            this.updateRelationDocStatusByApprovalDocumentId(caseDocumentRecordForUpdate.getDocumentCatalogCode(), "return", approvalAuditDto.getCaseId(), approvalAuditDto.getPartyId(), docId);
            Boolean f = del == 1 && completeIn == 1 && caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecordForUpdate) == 1;
            if (f) {
                if (!isCaseSourceRoll) {
                    result.put("success", "true");
                    result.put("msg", "成功");
                    return result;
                }
                if (!Constant.STRING_1.equals(currentRecord.get(0).getIsEditApproval())) {
                    result.put("workId", approvalAuditDto.getCaseId());
                }
                List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentCatalogCode(caseMainInfo.getId(), caseMainInfo, caseDocumentRecordForUpdate.getDocumentCatalogCode());
                String documentLinkObjectType = configBusiParamDocumentInfo.get(0).getDocumentLinkObjectType();
                if (Constant.STRING_2.equals(handleType) && Constant.STRING_2.equals(documentLinkObjectType)) {
                    result.put("workSubId", approvalAuditDto.getPartyId());
                }
                result.put("stepSignal", "STEP-RETURN");
                result.put("documentCatalogCode", caseDocumentRecordForUpdate.getDocumentCatalogCode());
            } else {
                throw new BusinessException("审批退回数据处理时出现异常");
            }
            // 生成文书
            // 文书审批退回 提交人钉钉提醒
            //sendDingAuditFinish(currentRecord,"NO");
            sendDingAuditFinishMsg(currentRecord, "NO");

            //工作台-消息提醒
            List<String> userIds = new ArrayList<>();
            userIds.add(currentRecord.get(0).getAddUserId());
            ConfigBusiParamDocumentInfo catalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(caseDocumentRecordForUpdate.getDocumentCatalogCode());
            sendAuditFinishRetiredPcMsg(approvalAuditDto.getCaseId(), caseDocumentRecordForUpdate.getDocumentCatalogCode(), catalogCode.getDocumentCatalogName(), currentRecord.get(0), caseMainInfo.getCaseOrgCode(), userIds);
            //涉刑移送审批退回处理
            if (DocumentKindEnum.DOC_KIND_DK1SXFZAJYSSPB.getCode().equals(catalogCode.getDocumentKindCode())) {
                updateLawCaseBaseInfoStatus(approvalAuditDto.getCaseId());
            }
            return result;
        }
        // 退回上一步操作
        String prior = "prior";
        if (prior.equals(approvalAuditDto.getReturnNode())) {
            // 查询上一环节时效
            List<CaseApprovalFlowRelation> priorflows = getPriorCaseApprovalFlow(currentRecord);
            if (priorflows.isEmpty()) {
                throw new BusinessException("未匹配到上一环节审批流配置信息");
            }
            //找出上一步操作记录,插入待审批表
            // 返回上个节点查询上个节点信息
            Example exampleComplete = new Example(CaseApprovalCompleteRecord.class);
            if (StringUtils.isBlank(approvalAuditDto.getPartyId())) {
                exampleComplete.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andGreaterThan("approvalNum", "0").andEqualTo("documentId", currentRecord.get(0).getDocumentId()).andEqualTo("flowRelationId", priorflows.get(0).getId());
            } else {
                exampleComplete.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andGreaterThan("approvalNum", "0").andEqualTo("documentId", currentRecord.get(0).getDocumentId()).andEqualTo("flowRelationId", priorflows.get(0).getId()).andEqualTo("partyId", approvalAuditDto.getPartyId());
            }
            //排序查询时间倒序
            exampleComplete.orderBy("approvalTime").desc();
            List<CaseApprovalCompleteRecord> caseApprovalCompleteRecords = caseApprovalCompleteRecordMapper.selectByExample(exampleComplete);
            if (caseApprovalCompleteRecords.isEmpty()) {
                throw new BusinessException("审批完成记录为空");
            }
            //判断审批记录是否存在
            boolean isExist = checkCaseApprovalWaitRecordIsExist(approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), approvalAuditDto.getPartyId());
            if (isExist) {
                throw new BusinessException("审批退回失败，待审批记录已存在!");
            }
            CaseApprovalWaitRecord newWaitNode = new CaseApprovalWaitRecord();
            BeanUtils.copyProperties(caseApprovalCompleteRecords.get(0), newWaitNode);
            newWaitNode.setId(StringUtils.uuid());
            newWaitNode.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
            if (StringUtils.isNotBlank(priorflows.get(0).getApprovalTerm())) {
                Integer term = priorflows.get(0).getApprovalTerm().contains("天") ? new Integer(priorflows.get(0).getApprovalTerm().substring(0, priorflows.get(0).getApprovalTerm().length() - 1)) : new Integer(priorflows.get(0).getApprovalTerm());
                newWaitNode.setApprovalCurrentLimitTime(term);
                newWaitNode.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
                newWaitNode.setFlowRelationId(priorflows.get(0).getId());
            }
            int newIn = caseApprovalWaitRecordMapper.insert(newWaitNode);
            Boolean f = (newIn == 1 && del == 1 && completeIn == 1);
            if (f) {
                result.put("documentCatalogCode", "");//看不懂用来干啥的，先这样吧，头疼
            } else {
                throw new BusinessException("审批退回数据处理时出现异常");
            }
        }
        return result;
    }

    /**
     * 描述： 移送案件
     *
     * @return
     * @author: zhengqiang
     * @date: 2023/1/16
     * @param: documentId
     * @param: caseId
     **/
    private void updateLawCaseBaseInfoStatus(String caseId) {
        CaseBaseInfoStatusUpdateDto updateDto = new CaseBaseInfoStatusUpdateDto(caseId, Constant.STRING_8);
        lawenforceBusinessService.updateLawCaseBaseInfoStatus(updateDto);
    }

    /**
     * 删除案源流转日志
     *
     * @param caseSourceRegisterMainInfo
     * @param caseMainInfo
     * @return
     * @author liyafeng
     * @date 2022/8/18
     */
    private void rmCaseSourceFlow(CaseSourceRegisterMainInfo caseSourceRegisterMainInfo, CaseMainInfoVo caseMainInfo) {
        CaseSourceFlowRecord caseSourceFlowRecord = caseSourceFlowRecordService.getLastCaseSourceFlowRecord(caseSourceRegisterMainInfo.getId());
        if (Constant.CASE_SOURCE_STAGE_LASP.equals(caseSourceFlowRecord.getFlowStageType()) || Constant.CASE_SOURCE_STAGE_BYLASP.equals(caseSourceFlowRecord.getFlowStageType())) {
            caseSourceFlowRecordMapper.deleteByPrimaryKey(caseSourceFlowRecord.getId());
        }
    }

    /**
     * 新审批 审批人钉钉消息（新加--兼容发送管理人员的政务钉钉信息）
     *
     * @param caseId
     * @param documentCatalogCode
     * @param term
     * @param userIdList
     */
    private void sendNewAuditDingMsg(String caseId, String documentCatalogCode, Integer term, List<String> userIdList) {
        //获取执法人员和领导的政务钉钉id
        //List<ZfAndManageUserInfoVO> list = xzzfInterfaceService.getZfAndManageUsersByUserIds(userIdList);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userIds", userIdList);
        if (!org.springframework.util.ObjectUtils.isEmpty(userIdList)) {
            List<MemberUserInfo> list = memberUserSignMapper.selectMemberUserInfoByUserIds(paramMap);
            List<CaseHandlePersonRecordVo> handlePersonRecordVos = caseHandlePersonRecordService.getCaseHandlePersonRecordListByCaseId(caseId);
            if (!handlePersonRecordVos.isEmpty()) {
                String hours = term * 24 + "小时";
                for (MemberUserInfo user : list) {
                    if (StringUtils.isNotBlank(user.getZzdAccountid())) {
                        this.sendDingMsg(caseId, documentCatalogCode, user.getRealName(), user.getZzdAccountid(), "newAudit", handlePersonRecordVos.get(0).getHandleOrgName(), hours);
                    }
                }
            }
        }
    }

    /**
     * 审批完成 钉钉提醒（新加--兼容发送管理人员的政务钉钉信息）
     *
     * @param currentRecord
     * @param flag
     */
    private void sendDingAuditFinishMsg(List<CaseApprovalWaitRecord> currentRecord, String flag) {
        List<String> userIds = new ArrayList<>();
        userIds.add(currentRecord.get(0).getAddUserId());
        //List<ZfAndManageUserInfoVO> list = xzzfInterfaceService.getZfAndManageUsersByUserIds(userIds);
        //调整为直接从member表中查询
        //查询审批人浙政钉id
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userIds", userIds);
        if (null != userIds && userIds.size() > 0) {
            List<MemberUserInfo> list = memberUserSignMapper.selectMemberUserInfoByUserIds(paramMap);
            if (list != null && !list.isEmpty() && StringUtils.isNotBlank(list.get(0).getZzdAccountid())) {
                String yes = "YES";
                // 审批人提醒
                UserDTO cu = UserUtil.getUserInfo();
                Map<String, Object> paramApprovalMap = new HashMap<>();
                paramApprovalMap.put("userIds", Collections.singleton(cu.getUserId().toString()));
                List<MemberUserInfo> approveUserlist = memberUserSignMapper.selectMemberUserInfoByUserIds(paramApprovalMap);
                if (!org.springframework.util.ObjectUtils.isEmpty(approveUserlist)) {
                    MemberUserInfo memberUserInfo = approveUserlist.get(0);
                    if (cu != null && StringUtils.isNotBlank(cu.getDingDingId())) {
                        this.sendDingMsg(currentRecord.get(0).getCaseId(), currentRecord.get(0).getDocumentId(), memberUserInfo.getRealName(), memberUserInfo.getZzdAccountid(), "auditPass");
                    }
                }
                // 提请人提醒
                for (MemberUserInfo user : list) {
                    if (StringUtils.isNotBlank(user.getZzdAccountid())) {
                        if (yes.equals(flag)) {
                            //发送消息
                            this.sendDingMsg(currentRecord.get(0).getCaseId(), currentRecord.get(0).getDocumentId(), user.getRealName(), user.getZzdAccountid(), "auditedPass");
                        } else {
                            //发送消息
                            this.sendDingMsg(currentRecord.get(0).getCaseId(), currentRecord.get(0).getDocumentId(), user.getRealName(), user.getZzdAccountid(), "auditRetired");
                        }
                    }
                }
            }
        }
    }

    /**
     * 审批完成 钉钉提醒
     *
     * @param currentRecord
     * @param flag
     */
    private void sendDingAuditFinish(List<CaseApprovalWaitRecord> currentRecord, String flag) {
        JSONObject baseInfoRequest = new JSONObject();
        List<String> userIds = new ArrayList<>();
        userIds.add(currentRecord.get(0).getAddUserId());
        baseInfoRequest.put("userIds", userIds);
        List<ZfPeopleBaseInfoVO> baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
        if (!baseInfo.isEmpty() && StringUtils.isNotBlank(baseInfo.get(0).getDingDingId())) {
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(currentRecord.get(0).getDocumentId());
            String yes = "YES";
            // 审批人提醒
            UserDTO cu = UserUtil.getUserInfo();
            /*if(StringUtils.isBlank(cu.getDingDingId())) {
                try {
                    String phoneNum = cu.getPhone();
                    String dingId = DingDingUtil.getAccountIdByMobile(phoneNum);
                    cu.setDingDingId(dingId);
                }catch (Exception e){
                    cu.setDingDingId("");
                }
            }*/
            if (cu != null && StringUtils.isNotBlank(cu.getDingDingId())) {
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("caseId", currentRecord.get(0).getCaseId());
                    jsonObject.put("documentCatalogCode", configBusiParamDocumentInfo.getDocumentCatalogCode());
                    //jsonObject.put("handleOrgName", handlePersonRecordVos.get(0).getHandleOrgName());
                    jsonObject.put("name", cu.getRealName());
                    jsonObject.put("documentCatalogName", configBusiParamDocumentInfo.getDocumentCatalogName());
                    jsonObject.put("dingDingId", cu.getDingDingId());
                    jsonObject.put("url", "");
                    jsonObject.put("dingMsgType", "auditPass");
                    BaseUtil.post(dingSendUrl, jsonObject);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //DingDingUtil.auditPassMsg(currentRecord.get(0).getCaseId(),configBusiParamDocumentInfo.getDocumentCatalogCode(),configBusiParamDocumentInfo.getDocumentCatalogName(), cu.getDingDingId(), cu.getRealName(), "");
            }
            // 提请人提醒
            for (ZfPeopleBaseInfoVO user : baseInfo) {
                if (StringUtils.isNotBlank(user.getDingDingId())) {
                    if (yes.equals(flag)) {
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("caseId", currentRecord.get(0).getCaseId());
                            jsonObject.put("documentCatalogCode", configBusiParamDocumentInfo.getDocumentCatalogCode());
                            //jsonObject.put("handleOrgName", handlePersonRecordVos.get(0).getHandleOrgName());
                            jsonObject.put("name", user.getName());
                            jsonObject.put("documentCatalogName", configBusiParamDocumentInfo.getDocumentCatalogName());
                            jsonObject.put("dingDingId", user.getDingDingId());
                            jsonObject.put("url", "");
                            jsonObject.put("dingMsgType", "auditedPass");
                            BaseUtil.post(dingSendUrl, jsonObject);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //DingDingUtil.auditedMsg(currentRecord.get(0).getCaseId(),configBusiParamDocumentInfo.getDocumentCatalogCode(),configBusiParamDocumentInfo.getDocumentCatalogName(), user.getName(), user.getDingDingId(), "");
                    } else {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("caseId", currentRecord.get(0).getCaseId());
                        jsonObject.put("documentCatalogCode", configBusiParamDocumentInfo.getDocumentCatalogCode());
                        //jsonObject.put("handleOrgName", handlePersonRecordVos.get(0).getHandleOrgName());
                        jsonObject.put("name", user.getName());
                        jsonObject.put("documentCatalogName", configBusiParamDocumentInfo.getDocumentCatalogName());
                        jsonObject.put("dingDingId", user.getDingDingId());
                        jsonObject.put("url", "");
                        jsonObject.put("dingMsgType", "auditRetired");
                        BaseUtil.post(dingSendUrl, jsonObject);
                        //DingDingUtil.auditRetiredMsg(currentRecord.get(0).getCaseId(),configBusiParamDocumentInfo.getDocumentCatalogCode(),configBusiParamDocumentInfo.getDocumentCatalogName(), user.getDingDingId(),user.getName() , "");
                    }
                }
            }
        }
    }

    /**
     * 清空审批意见
     *
     * @param caseDocumentRecordForUpdate
     */
    private void clearOpinion(CaseDocumentRecord caseDocumentRecordForUpdate) {
        JSONObject jsonObject = JSON.parseObject(caseDocumentRecordForUpdate.getDocumentContent());
        HashMap<String, Object> jsonMap = new HashMap<>(16);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            jsonMap.put(entry.getKey(), entry.getValue());
        }
        for (OpinionType ot : OpinionType.values()) {
            jsonMap.put(ot.getAuditUserIdCode(), "");
            jsonMap.put(ot.getDocCode(), "");
            jsonMap.put(ot.getAuditTimeCode(), "");
        }
        caseDocumentRecordForUpdate.setDocumentContent(JSONObject.toJSON(jsonMap).toString());
    }

    /**
     * 清空审批意见(裁执分离)
     *
     * @param executeDocumentRecordForUpdate
     */
    private void clearExecuteOpinion(ExecuteDocumentRecord executeDocumentRecordForUpdate) {
        JSONObject jsonObject = JSON.parseObject(executeDocumentRecordForUpdate.getDocumentContent());
        HashMap<String, Object> jsonMap = new HashMap<>(16);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            jsonMap.put(entry.getKey(), entry.getValue());
        }
        for (OpinionType ot : OpinionType.values()) {
            jsonMap.put(ot.getAuditUserIdCode(), "");
            jsonMap.put(ot.getDocCode(), "");
            jsonMap.put(ot.getAuditTimeCode(), "");
        }
        executeDocumentRecordForUpdate.setDocumentContent(JSONObject.toJSON(jsonMap).toString());
    }

    /**
     * 生成文书
     *
     * @param relationId
     * @param caseId
     * @param docId
     * @param caseDocumentRecords
     * @param currentOpinion
     * @param islast
     * @param approvalStatus
     * @return
     */
    private Map<String, Object> makeDoc(String relationId, String caseId, String docId, CaseDocumentRecord caseDocumentRecords, String currentOpinion, boolean islast, String approvalStatus, String partyId, String caseAssistId, String isEditApproval, String documentId, String exceptionCaseDocumentSerialKey) {
        StageDocCommonOperateSaveDto saveDto = new StageDocCommonOperateSaveDto();
        saveDto.setCaseId(caseId);
        saveDto.setPartyId(partyId);
        saveDto.setDocumentCatalogCode(docId);
        saveDto.setCaseAssistId(caseAssistId);
        //设置审批异常文号标识
        saveDto.setExceptionCaseDocumentSerialKey(exceptionCaseDocumentSerialKey);
        JSONObject jsonObject = JSON.parseObject(caseDocumentRecords.getDocumentContent());
        HashMap<String, Object> jsonMap = new HashMap<>(16);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            jsonMap.put(entry.getKey(), entry.getValue());
        }
        UserDTO userDTO = UserUtil.getUserInfo();
        if (!Constant.STRING_1.equals(isEditApproval)) {
            //如果是结案报告，则更新文书中的日期
            this.updateCaseEndDate(caseId, docId, jsonMap, islast);
            // 当前节点审批意见
            CaseApprovalFlowRelation caseApprovalFlowRelation = caseDocuApprovalFolwRelationMapper.selectByPrimaryKey(relationId);
            String sign = iRegisterCommonService.getHandleSignData(userDTO.getUserId().toString());
            if (caseApprovalFlowRelation != null) {
                for (OpinionType ot : OpinionType.values()) {
                    if (caseApprovalFlowRelation.getApprovalOpinionType().equals(ot.getCode())) {
                        jsonMap.put(ot.getDocCode(), currentOpinion);
                        jsonMap.put(ot.getAuditTimeCode(), LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
                        jsonMap.put(ot.getAuditUserIdCode(), sign);
                    }
                }
            }
        }

        saveDto.setIsUpdateRelationTable(Constant.STRING_0);
        saveDto.setDocumentApprovalStatus(approvalStatus);
        if (islast) {
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(docId);
            String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
            if (DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(documentKindCode)) {
                String areaCode = userDTO.getAreaCode();
                try {
                    //调用行政行为码赋码接口 同时生成二维码 与 条形码
                    ActsCodeDto actsCodeDto = new ActsCodeDto();
                    actsCodeDto.setCaseId(caseId);
                    //caseActsCodeInfoService.saveCaseActsCodeInfo(actsCodeDto);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
           /* if(Constant.STRING_1.equals(isEditApproval)){
                caseDocumentRecordService.modifyDocumentRecordAfterApproval(documentId);
            }*/
            saveDto.setCloseSignal("CLOSE-TRIGGER-APPROVAL-PASS");
        }
        //是否是修改文书
        saveDto.setIsEditFile(isEditApproval);
        saveDto.setDocId(documentId);
        saveDto.setDataMap(jsonMap);
        saveDto.setRelationDocumentId(caseDocumentRecords.getRelationDocumentId());
        return stageDocCommonOperateService.saveDocInfo(saveDto);
    }

    private Map<String, Object> makeDocAuto(String relationId, String caseId, String docId, CaseDocumentRecord caseDocumentRecords, String currentOpinion, boolean islast, String approvalStatus, String partyId, String caseAssistId, String userId) {
        UserDTO userDTO = UserUtil.getUserInfo();
        StageDocCommonOperateSaveDto saveDto = new StageDocCommonOperateSaveDto();
        saveDto.setCaseId(caseId);
        saveDto.setPartyId(partyId);
        saveDto.setDocumentCatalogCode(docId);
        saveDto.setCaseAssistId(caseAssistId);
        JSONObject jsonObject = JSON.parseObject(caseDocumentRecords.getDocumentContent());
        HashMap<String, Object> jsonMap = new HashMap<>(16);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            jsonMap.put(entry.getKey(), entry.getValue());
        }
        //如果是结案报告，则更新文书中的日期
        this.updateCaseEndDate(caseId, docId, jsonMap, islast);

        // 当前节点审批意见
        CaseApprovalFlowRelation caseApprovalFlowRelation = caseDocuApprovalFolwRelationMapper.selectByPrimaryKey(relationId);
        if (StringUtils.isBlank(userId)) {
            userId = userDTO.getUserId().toString();
        }
        String sign = iRegisterCommonService.getHandleSignData(userId);
        if (caseApprovalFlowRelation != null) {
            for (OpinionType ot : OpinionType.values()) {
                if (caseApprovalFlowRelation.getApprovalOpinionType().equals(ot.getCode())) {
                    jsonMap.put(ot.getDocCode(), currentOpinion);
                    jsonMap.put(ot.getAuditTimeCode(), LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
                    jsonMap.put(ot.getAuditUserIdCode(), sign);
                }
            }
        }
        saveDto.setIsUpdateRelationTable(Constant.STRING_0);
        saveDto.setDocumentApprovalStatus(approvalStatus);
        if (islast) {
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(docId);
            String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
            if (DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(documentKindCode)) {
                String areaCode = userDTO.getAreaCode();
                try {
                    //调用行政行为码赋码接口 同时生成二维码 与 条形码
                    ActsCodeDto actsCodeDto = new ActsCodeDto();
                    actsCodeDto.setCaseId(caseId);
                    //caseActsCodeInfoService.saveCaseActsCodeInfo(actsCodeDto);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            saveDto.setCloseSignal("CLOSE-TRIGGER-APPROVAL-PASS");
        }
        //CaseMainInfo caseMainInfo=caseMainInfoMapper.selectByPrimaryKey(caseId);
        if ("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal())) {
            CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId, DocumentKindEnum.DOC_KIND_LASPB.getCode());
            jsonMap.put("caseNumber", caseDocumentRecord.getDocumentNumber());
        }
        saveDto.setDataMap(jsonMap);
        return stageDocCommonOperateService.saveDocInfoAuto(saveDto);
    }

    /**
     * 结案日期取值：结案报告审批通过的日期
     * 操作：
     * 在最后一个审批环节，更改结案报告文书中的结案日期
     */
    private void updateCaseEndDate(String caseId, String docId, HashMap<String, Object> contentJsonMap, boolean isLast) {
        if (isLast) {
            ConfigBusiParamDocumentInfo configInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(docId);
            if (DocumentKindEnum.DOC_KIND_JABG.getCode().equals(configInfo.getDocumentKindCode())) {
                contentJsonMap.put("AJJABG_JARQ", cn.hutool.core.date.DateUtil.format(LocalDateTime.now(), DatePattern.CHINESE_DATE_PATTERN));
                CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
                if (caseMainInfo.getCaseEndTime() == null) {
                    caseMainInfo.setCaseEndTime(LocalDateTime.now());
                    caseMainInfoMapper.updateByPrimaryKeySelective(caseMainInfo);
                    CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
                    //宽表添加结案日期
                    updateCaseMainDetailInfo.setCaseId(caseId);
                    updateCaseMainDetailInfo.setCaseFinishDate(LocalDate.now());
                    caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);
                }

            } else if (DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(configInfo.getDocumentKindCode())) {
                contentJsonMap.put("caseRegistTime", DateUtils.formatDate(new Date(), DateUtil.date_sdf_wz_format));
            }

        }
    }

    /**
     * 生成文书
     *
     * @param relationId
     * @param executeId
     * @param docId
     * @param executeDocumentRecord
     * @param currentOpinion
     * @param islast
     * @param approvalStatus
     * @return
     */
    private Map<String, Object> makeExecuteDoc(String relationId, String executeId, String docId, ExecuteDocumentRecord executeDocumentRecord, String currentOpinion, boolean islast, String approvalStatus, String partyId) {
        ExecuteDocCommonOperateSaveDto saveDto = new ExecuteDocCommonOperateSaveDto();
        saveDto.setExecuteId(executeId);
        saveDto.setPartyId(partyId);
        saveDto.setDocumentCatalogCode(docId);
        JSONObject jsonObject = JSON.parseObject(executeDocumentRecord.getDocumentContent());
        HashMap<String, Object> jsonMap = new HashMap<>(16);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            jsonMap.put(entry.getKey(), entry.getValue());
        }
        UserDTO userDTO = UserUtil.getUserInfo();
        // 当前节点审批意见
        CaseApprovalFlowRelation caseApprovalFlowRelation = caseDocuApprovalFolwRelationMapper.selectByPrimaryKey(relationId);
        String sign = iRegisterCommonService.getHandleSignData(userDTO.getUserId().toString());
        if (caseApprovalFlowRelation != null) {
            for (OpinionType ot : OpinionType.values()) {
                if (caseApprovalFlowRelation.getApprovalOpinionType().equals(ot.getCode())) {
                    jsonMap.put(ot.getDocCode(), currentOpinion);
                    jsonMap.put(ot.getAuditTimeCode(), LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
                    jsonMap.put(ot.getAuditUserIdCode(), sign);
                }
            }
        }
        saveDto.setDataMap(jsonMap);
        saveDto.setIsUpdateRelationTable(Constant.STRING_0);
        saveDto.setDocumentApprovalStatus(approvalStatus);
        if (islast) {
            saveDto.setCloseSignal("CLOSE-TRIGGER-APPROVAL-PASS");
        }
        return executeDocCommonOperateService.saveDocInfo(saveDto);
    }


    @Override
    public List<NextAuditUserVo> getNextNodeUser(AuditNextUserQueryDto dto) {
        List<CaseApprovalWaitRecord> currentRecord = null;
        if (StringUtils.isNotBlank(dto.getDocId())) {
            Example example = new Example(CaseApprovalWaitRecord.class);
            example.createCriteria().andEqualTo("caseId", dto.getCaseId()).andEqualTo("docId", dto.getDocId());
            currentRecord = caseApprovalWaitRecordMapper.selectByExample(example);
        }
        if (ObjectUtils.isEmpty(currentRecord)) {
            Example example = new Example(CaseApprovalWaitRecord.class);
            if (StringUtils.isBlank(dto.getPartyId())) {
                example.createCriteria().andEqualTo("caseId", dto.getCaseId()).andEqualTo("documentId", dto.getDocumentCatalogCode());
            } else {
                example.createCriteria().andEqualTo("caseId", dto.getCaseId()).andEqualTo("documentId", dto.getDocumentCatalogCode()).andEqualTo("partyId", dto.getPartyId());
            }
            currentRecord = caseApprovalWaitRecordMapper.selectByExample(example);
        }

        List<NextAuditUserVo> nextAuditUsers = new ArrayList<>();
        CaseApprovalWaitRecord caseApprovalWaitRecord = null;
        if (null != currentRecord && currentRecord.size() > 0) {
            caseApprovalWaitRecord = currentRecord.get(0);
        }
        //查询下一环节关联
        String documentCatalogCode = dto.getDocumentCatalogCode();
        if (Constant.STRING_1.equals(dto.getIsMerge())) {
            CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(dto.getCaseId());
            documentCatalogCode = getMergeDocumentCatalogCode(caseMainDetailInfo.getInvestConclusion());
            //documentCatalogCode="DC1A0223300CFGZSPB000000001";
        }
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(caseApprovalWaitRecord, documentCatalogCode);
        //判断是否当前文书最后一个审批节点校验
        if (nextFlow.isEmpty()) {
            NextAuditUserVo vo = new NextAuditUserVo();
            vo.setIsFinal("YES");
            nextAuditUsers.add(vo);
            return nextAuditUsers;
        }
        // 两种 方式调用member服务
        // 调用 member服务接口 根据角色 领域 执法区域 查询 用户信息
        // 调用List<User> users = userFeignApi.selectUserListByOgrCodeAndRoleName(userDTO.getOrgCode(),nextFlow.get(0).getApprovalRole());调用//
        //第二种 "/api/v2/member/zfPeople/yy/getZfPeopleBaseInfoList" 直接取
        CaseApprovalFlowRelation flowRelation = nextFlow.get(0);
        //判断是否配置自动审批
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(dto.getCaseId());
        //裁执分离可能没有案件信息
        if (ObjectUtil.isNotEmpty(caseMainInfo)) {
            String roleId = flowRelation.getApprovalRole();
            String caseType = caseMainInfo.getCaseType();
            if (Constant.STRING_3.equals(caseType) || Constant.STRING_4.equals(caseType)) {
                NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(caseMainInfo, roleId, documentCatalogCode);
                if (null != vo) {
                    nextAuditUsers.add(vo);
                    return nextAuditUsers;
                }
            }
        }


        boolean isApprovalCenter = false;
        String one = "1";
        if (one.equals(flowRelation.getIsApprovalCenter())) {
            isApprovalCenter = true;
        }
        //获取上次选择的审批人的code
        String checkCode = getLastCheckCode(isApprovalCenter, flowRelation, dto);
        if (!isApprovalCenter) {
            if ("2".equals(dto.getType())) {//裁执分离
                getExecuteNextUsers(nextAuditUsers, nextFlow, dto.getCaseId(), checkCode);
            } else {//案件类型
                getNextUsers(nextAuditUsers, nextFlow, dto.getCaseId(), checkCode);
            }
        } else {
            if ("2".equals(dto.getType())) {//裁执分离

            } else {//案件类型
                getApprovalCenterNextUsers(nextAuditUsers, flowRelation, dto.getCaseId(), checkCode);
            }
        }
        // 只有一个人默认选中.
        if (nextAuditUsers.size() == 1) {
            nextAuditUsers.get(0).setIsCheck(Constant.STRING_1);
        }
        // 有选中的人放到List的第一个.
        if (nextAuditUsers.size() > 1 && StringUtils.isNotEmpty(checkCode)) {
            nextAuditUsers = nextAuditUsers.stream().sorted((a, b) -> {
                return b.getIsCheck().compareTo(a.getIsCheck());
            }).collect(Collectors.toList());
        }
        //未提交查询第一个环节
        return nextAuditUsers;
    }

    /**
     * 获取合并处罚参照文书目录编码
     *
     * @param investConclusion
     * @return {@link String}
     * @author liyafeng
     * @date 2023/5/5
     */
    private String getMergeDocumentCatalogCode(String investConclusion) {
        String documentCatalogCode = "DC1A0223300CFGZSPB000000001";
        if (Constant.STRING_2.equals(investConclusion)) {
            documentCatalogCode = "DC1A0223300BYCFGZSPB0000001";
        }
        return documentCatalogCode;
    }

    /**
     * 获取上次选择的审批人的code
     *
     * @param isApprovalCenter
     * @param flowRelation
     * @return {@link String}
     * @author liyafeng
     * @date 2022/7/11
     */
    private String getLastCheckCode(boolean isApprovalCenter, CaseApprovalFlowRelation flowRelation, AuditNextUserQueryDto dto) {
        String checkCode = "";
        UserDTO userDTO = UserUtil.getUserInfo();
        String orderNum = flowRelation.getApprovalOrderNum();
        Example completeExample = new Example(CaseApprovalCompleteRecord.class);
        completeExample.createCriteria().andEqualTo("approvalNum", orderNum).andEqualTo("documentId", dto.getDocumentCatalogCode()).andEqualTo("addUserId", userDTO.getUserId().toString());
        completeExample.setOrderByClause("approval_time desc");
        List<CaseApprovalCompleteRecord> caseApprovalCompleteRecordList = caseApprovalCompleteRecordMapper.selectByExample(completeExample);
        if (null != caseApprovalCompleteRecordList && caseApprovalCompleteRecordList.size() > 0) {
            checkCode = caseApprovalCompleteRecordList.get(0).getApprovalUserId();
            if (isApprovalCenter) {
                checkCode = caseApprovalCompleteRecordList.get(0).getApprovalOrgCode();
            }
        }

        return checkCode;
    }

    /**
     * 查询下一环节审批人
     *
     * @param nextAuditUsers
     * @param nextFlow
     */
    private void getNextUsers(List<NextAuditUserVo> nextAuditUsers, List<CaseApprovalFlowRelation> nextFlow, String caseId, String checkCode) {
        //查询上一次审批
        JSONObject baseInfoRequest = new JSONObject();
        baseInfoRequest.put("pageNum", 1);
        baseInfoRequest.put("length", 1000);
        List<Long> roleCodes = new ArrayList<>();
        List<String> orgCodes = new ArrayList<>();
        List<String> deptCodes = new ArrayList<>();
        CaseApprovalFlowRelation flowRelation = nextFlow.get(0);
        //roleCodes.add(Long.valueOf(flowRelation.getApprovalRole()));
        //可能出现上级审完分配给下级的情况 故不从loginUser取orgCode deptCodes暂时不考虑
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        //UserDTO loginUser = UserUtil.getUserInfo();
        String orgCode = caseMainInfo.getCaseOrgCode();
        orgCodes.add(orgCode);
        //deptCodes.add(loginUser.getDeptCode());
        // 层级处理
        // 本级
        String one = "1";
        String two = "2";
        if (one.equals(flowRelation.getApprovalLevel())) {
            baseInfoRequest.put("roles", roleCodes);
            baseInfoRequest.put("orgCodes", orgCodes);
            // 审批范围
            /*if (two.equals(flowRelation.getApprovalScope())){
                baseInfoRequest.put("deptCodes", deptCodes);
            }*/
            baseInfoRequest.put("status", "1");
            //List<ZfPeopleBaseInfoVO> users = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("orgCode", orgCode);
            paramMap.put("roleId", flowRelation.getApprovalRole());
            //根据机构、角色查询用户
            List<MemberUserVo> memberUserVos = new ArrayList<>();
            //承办机构负责人需要限制执法人员或行政机关负责人
//            if (Constant.ORGANIZER_ROLE_ID.equals(flowRelation.getApprovalRole())) {
//                memberUserVos = caseApprovalWaitRecordMapper.selectMemberUserVoList(paramMap);
//            } else {
//
//            }
            //20240102 交付经理确认，无执法证也可审批，只需限制对应的角色即可
            //如需要根据角色限制是否必须要执法证可以判断flowRelation.getApprovalRole()角色id
            //然后执行 memberUserVos = caseApprovalWaitRecordMapper.selectMemberUserVoList(paramMap); 获取限制角色必须包含执法证
            memberUserVos = caseApprovalWaitRecordMapper.selectMemberUserVoListNoAgent(paramMap);
            for (MemberUserVo user : memberUserVos) {
                NextAuditUserVo nextAuditUserVo = new NextAuditUserVo();
                String userId = user.getUserId();
                nextAuditUserVo.setUserId(userId);
                nextAuditUserVo.setIsFinal("NO");
                nextAuditUserVo.setRealName(user.getRealName());
                nextAuditUserVo.setIsCheck(Constant.STRING_0);
                nextAuditUserVo.setApprovalRoleName(flowRelation.getApprovalRoleName());
                if (StringUtils.isNotBlank(checkCode)) {
                    if (Arrays.asList(checkCode.split(",")).contains(userId)) {
                        nextAuditUserVo.setIsCheck(Constant.STRING_1);
                    }
                }
                nextAuditUserVo.setIsAutoApproval(Constant.STRING_0);
                nextAuditUsers.add(nextAuditUserVo);
            }
        } else {
            // 审批层级-字典值;1 本级，2 区县 ，3 地市 ，4 省级
            String three = "3";
            String four = "4";
            baseInfoRequest.clear();
            String areaCode = orgCode.split("_")[0];
            if (two.equals(flowRelation.getApprovalLevel())) {
                areaCode = areaCode.substring(0, 6).concat("000000");
            }
            if (three.equals(flowRelation.getApprovalLevel())) {
                areaCode = areaCode.substring(0, 4).concat("00000000");
            }
            if (four.equals(flowRelation.getApprovalLevel())) {
                areaCode = areaCode.substring(0, 2).concat("0000000000");
            }
            baseInfoRequest.put("areaCode", areaCode);
            CaseMainInfo mainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
            baseInfoRequest.put("territoryCode", mainInfo.getCaseTerritoryCode());
            baseInfoRequest.put("roleId", flowRelation.getApprovalRole());
            List<CaseUserVo> vos = getCaseUserList(baseInfoRequest);
            for (CaseUserVo user : vos) {
                NextAuditUserVo nextAuditUserVo = new NextAuditUserVo();
                nextAuditUserVo.setUserId(user.getUserId());
                nextAuditUserVo.setIsFinal("NO");
                nextAuditUserVo.setRealName(user.getRealName());
                nextAuditUserVo.setIsCheck(Constant.STRING_0);
                nextAuditUserVo.setApprovalRoleName(flowRelation.getApprovalRoleName());
                if (StringUtils.isNotBlank(checkCode)) {
                    if (Arrays.asList(checkCode.split(",")).contains(user.getUserId())) {
                        nextAuditUserVo.setIsCheck(Constant.STRING_1);
                    }
                }
                nextAuditUserVo.setApprovalRoleName(flowRelation.getApprovalRoleName());
                nextAuditUserVo.setIsAutoApproval(Constant.STRING_0);
                nextAuditUsers.add(nextAuditUserVo);
            }
        }
    }

    /**
     * 查询下一环节审批人
     *
     * @param nextAuditUsers
     * @param nextFlow
     */
    private void getExecuteNextUsers(List<NextAuditUserVo> nextAuditUsers, List<CaseApprovalFlowRelation> nextFlow, String caseId, String checkCode) {
        //查询上一次审批
        JSONObject baseInfoRequest = new JSONObject();
        baseInfoRequest.put("pageNum", 1);
        baseInfoRequest.put("length", 1000);
        List<String> roleCodes = new ArrayList<>();
        List<String> orgCodes = new ArrayList<>();
        List<String> deptCodes = new ArrayList<>();
        CaseApprovalFlowRelation flowRelation = nextFlow.get(0);
        roleCodes.add(flowRelation.getApprovalRole());
        //可能出现上级审完分配给下级的情况 故不从loginUser取orgCode deptCodes暂时不考虑
        ExecuteMainInfo executeMainInfo = executeMainInfoService.getByExecuteId(caseId);
        //UserDTO loginUser = UserUtil.getUserInfo();
        String orgCode = executeMainInfo.getExecuteOrgCode();
        orgCodes.add(orgCode);
        //deptCodes.add(loginUser.getDeptCode());
        // 层级处理
        // 本级
        String one = "1";
        String two = "2";
        if (one.equals(flowRelation.getApprovalLevel())) {
            baseInfoRequest.put("roles", roleCodes);
            baseInfoRequest.put("orgCodes", orgCodes);
            // 审批范围
            /*if (two.equals(flowRelation.getApprovalScope())){
                baseInfoRequest.put("deptCodes", deptCodes);
            }*/
            baseInfoRequest.put("status", "1");
            //List<ZfPeopleBaseInfoVO> users = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("orgCode", orgCode);
            paramMap.put("roleId", flowRelation.getApprovalRole());
            //根据机构、角色查询用户
            List<MemberUserVo> memberUserVos = new ArrayList<>();
            if (!Constant.STRING_3.equals(flowRelation.getApprovalOrderNum())) {
                memberUserVos = caseApprovalWaitRecordMapper.selectMemberUserVoList(paramMap);
            } else {
                memberUserVos = caseApprovalWaitRecordMapper.selectMemberUserVoListNoAgent(paramMap);
            }
            for (MemberUserVo user : memberUserVos) {
                NextAuditUserVo nextAuditUserVo = new NextAuditUserVo();
                String userId = user.getUserId();
                nextAuditUserVo.setUserId(userId);
                nextAuditUserVo.setIsFinal("NO");
                nextAuditUserVo.setRealName(user.getRealName());
                nextAuditUserVo.setIsCheck(Constant.STRING_0);
                nextAuditUserVo.setApprovalRoleName(flowRelation.getApprovalRoleName());
                if (StringUtils.isNotBlank(checkCode)) {
                    if (Arrays.asList(checkCode.split(",")).contains(userId)) {
                        nextAuditUserVo.setIsCheck(Constant.STRING_1);
                    }
                }
                nextAuditUsers.add(nextAuditUserVo);
            }
        } else {
            // 审批层级-字典值;1 本级，2 区县 ，3 地市 ，4 省级
            String three = "3";
            String four = "4";
            baseInfoRequest.clear();
            String areaCode = orgCode.split("_")[0];
            if (two.equals(flowRelation.getApprovalLevel())) {
                areaCode = areaCode.substring(0, 6).concat("000000");
            }
            if (three.equals(flowRelation.getApprovalLevel())) {
                areaCode = areaCode.substring(0, 4).concat("00000000");
            }
            if (four.equals(flowRelation.getApprovalLevel())) {
                areaCode = areaCode.substring(0, 2).concat("0000000000");
            }
            baseInfoRequest.put("areaCode", areaCode);
            ExecuteMainInfo mainInfo = executeMainInfoService.getByExecuteId(caseId);
            // 获取条线信息
            LineTerritoryInfoVo lineTerritoryInfoVo = sysDepartParamService.getLineInfoByOrgCodeAndLineCode(orgCode, "", executeMainInfo.getLineCode());
            baseInfoRequest.put("territoryCode", lineTerritoryInfoVo.getTerritoryCode());
            baseInfoRequest.put("roleId", flowRelation.getApprovalRole());
            List<CaseUserVo> vos = getCaseUserList(baseInfoRequest);
            for (CaseUserVo user : vos) {
                NextAuditUserVo nextAuditUserVo = new NextAuditUserVo();
                nextAuditUserVo.setUserId(user.getUserId());
                nextAuditUserVo.setIsFinal("NO");
                nextAuditUserVo.setRealName(user.getRealName());
                nextAuditUserVo.setIsCheck(Constant.STRING_0);
                nextAuditUserVo.setApprovalRoleName(flowRelation.getApprovalRoleName());
                if (StringUtils.isNotBlank(checkCode)) {
                    if (Arrays.asList(checkCode.split(",")).contains(user.getUserId())) {
                        nextAuditUserVo.setIsCheck(Constant.STRING_1);
                    }
                }
                nextAuditUserVo.setApprovalRoleName(flowRelation.getApprovalRoleName());
                nextAuditUsers.add(nextAuditUserVo);
            }
        }
    }

    /**
     * 查询下一环节审批人（联合法制审核）
     *
     * @param nextAuditUsers
     * @param flowRelation
     * @param caseId
     */
    private void getApprovalCenterNextUsers(List<NextAuditUserVo> nextAuditUsers, CaseApprovalFlowRelation flowRelation, String caseId, String checkCode) {
        JSONObject baseInfoRequest = new JSONObject();
        baseInfoRequest.put("pageNum", 1);
        baseInfoRequest.put("length", 1000);
        /*List<Long> roleCodes = new ArrayList<>();
        List<String> orgCodes = new ArrayList<>();
        List<String> deptCodes = new ArrayList<>();
        roleCodes.add(Long.valueOf(caseApprovalCenterRole));
        UserDTO loginUser = UserUtil.getUserInfo();
        orgCodes.add(loginUser.getOrgCode());
        deptCodes.add(loginUser.getDeptCode());*/
        UserDTO loginUser = UserUtil.getUserInfo();
        // 层级处理
        // 本级
        String one = "1";
        String two = "2";
        /*if (one.equals(flowRelation.getApprovalLevel())){
            baseInfoRequest.put("roles", roleCodes);
            baseInfoRequest.put("orgCodes", orgCodes);

            // 审批范围
            if (two.equals(flowRelation.getApprovalScope())){
                baseInfoRequest.put("deptCodes", deptCodes);
            }
            baseInfoRequest.put("status", "1");
            List<ZfPeopleBaseInfoVO> users = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
            if (!users.isEmpty()){
                StringJoiner stringJoiner = new StringJoiner(",");
                for (ZfPeopleBaseInfoVO user : users) {
                    stringJoiner.add(user.getUserId());
                }
                NextAuditUserVo nextAuditUserVo = new NextAuditUserVo();
                nextAuditUserVo.setUserId(stringJoiner.toString());
                nextAuditUserVo.setIsFinal("NO");
                nextAuditUserVo.setRealName("联合法制审核（"+loginUser.getOrgName()+"）");
                nextAuditUserVo.setApprovalCenterOrgCode(loginUser.getOrgCode());
                nextAuditUserVo.setIsApprovalCenter("1");
                nextAuditUsers.add(nextAuditUserVo);
            }
        }else {*/
        // 审批层级-字典值;1 本级，2 区县 ，3 地市 ，4 省级
        String three = "3";
        String four = "4";
        baseInfoRequest.clear();
        String areaCode = loginUser.getOrgCode().split("_")[0];
        //String areaCode="331001000000";
        //根据areacode 查询联合法制审核配置信息
        Map<String, Object> paramMap = new HashMap<>();
        System.out.println("ApprovalLevel---------------------" + flowRelation.getApprovalLevel());
        if (one.equals(flowRelation.getApprovalLevel())) {
            System.out.println("one---------------------" + areaCode.substring(0, 9));
            areaCode = areaCode.substring(0, 9).concat("000");
            System.out.println("one---------------------" + areaCode);
        }
        if (two.equals(flowRelation.getApprovalLevel())) {
            areaCode = areaCode.substring(0, 6).concat("000000");
            System.out.println("two---------------------" + areaCode);
        }
        if (three.equals(flowRelation.getApprovalLevel())) {
            areaCode = areaCode.substring(0, 4).concat("00000000");
            System.out.println("three---------------------" + areaCode);
        }
        if (four.equals(flowRelation.getApprovalLevel())) {
            areaCode = areaCode.substring(0, 2).concat("0000000000");
            System.out.println("four---------------------" + areaCode);
        }
        //登录的areaCode不准确，从机构编码里面截取
        String splitAreaCode = loginUser.getOrgCode().split("_")[0];
        System.out.println("splitAreaCode---------------------" + splitAreaCode);
        System.out.println("areaCode---------------------" + areaCode);
        System.out.println("OrgCode---------------------" + loginUser.getOrgCode());
        paramMap.put("applyAreaCode", splitAreaCode);
        List<ConfigCaseApprovalCenterVo> configCaseApprovalCenters = configCaseApprovalCenterMapper.selectConfigCaseApprovalCentersByMap(paramMap);
        if (null == configCaseApprovalCenters || configCaseApprovalCenters.size() == 0) {
            //如果根据机构编码截取的区划编码查不到联合法制审核配置，则根据用户区划编码查询（兼容解决机构编码有误问题）
            paramMap.put("applyAreaCode", loginUser.getAreaCode());
            configCaseApprovalCenters = configCaseApprovalCenterMapper.selectConfigCaseApprovalCentersByMap(paramMap);
            if (null == configCaseApprovalCenters || configCaseApprovalCenters.size() == 0) {
                throw new BusinessException("联合法制审核配置为空，请联系管理员进行配置！");
            }
        }
        Example example = new Example(CaseReasonMainRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", "1");
        List<CaseReasonMainRecord> caseReasonMainRecordList = caseReasonMainRecordMapper.selectByExample(example);
        String caseReasonCode = caseReasonMainRecordList.get(0).getCaseReasonCode();
        String territoryCode = caseReasonMainRecordList.get(0).getTerritoryCode();
        Example centerExample = new Example(ConfigCaseApprovalCenterLine.class);
        centerExample.createCriteria().andEqualTo("reasonNodeCode", caseReasonCode).andEqualTo("configId", configCaseApprovalCenters.get(0).getId());
        List<ConfigCaseApprovalCenterLine> configCaseApprovalCenterLines = configCaseApprovalCenterLineMapper.selectByExample(centerExample);
        if (null != configCaseApprovalCenterLines && configCaseApprovalCenterLines.size() > 0) {
            territoryCode = configCaseApprovalCenterLines.get(0).getApprovalTerritoryCode();
        } else {
            territoryCode = territoryCode + ",A022";
        }
        //获取上级areaCode
        List<String> supAreaCodeList = memberUserSignMapper.selectSupAreaCode(loginUser.getAreaCode());
        if (supAreaCodeList == null || supAreaCodeList.size() == 0) {
            throw new BusinessException("未找到上级区划编码！");

        }
            /*baseInfoRequest.put("areaCode",supAreaCodeList.get(0));
            baseInfoRequest.put("territoryCode",territoryCode);
            baseInfoRequest.put("roleId",caseApprovalCenterRole);*/
        //List<CaseUserVo> vos  =  getCaseUserList(baseInfoRequest);
        Map<String, Object> centerOrgParamMap = new HashMap<>();
        centerOrgParamMap.put("areaCode", supAreaCodeList.get(0));

        centerOrgParamMap.put("territoryCodes", Arrays.asList(territoryCode.split(",")));
        List<MemberOrgCenterVo> memberOrgCenterVos = memberUserSignMapper.selectMemberOrgCenterVo(centerOrgParamMap);
        if (memberOrgCenterVos != null && memberOrgCenterVos.size() > 0) {
            for (MemberOrgCenterVo memberOrgCenterVo : memberOrgCenterVos) {
                Map<String, Object> userParamMap = new HashMap<>();
                userParamMap.put("orgCode", memberOrgCenterVo.getOrgCode());
                userParamMap.put("roleId", caseApprovalCenterRole);
                List<MemberUserCenterVo> memberUserCenterVos = memberUserSignMapper.selectMemberUserCenterVo(userParamMap);
                //NextAuditUserVo nextAuditUserVo = new NextAuditUserVo();
                Set<String> set = new LinkedHashSet<>();
                for (MemberUserCenterVo user : memberUserCenterVos) {
                    set.add(user.getOrgName());
                }
                for (String orgName : set) {
                    NextAuditUserVo nextAuditUserVo = new NextAuditUserVo();
                    String userId = "";
                    String orgCode = "";
                    for (MemberUserCenterVo user : memberUserCenterVos) {
                        log.info("orgName:{},user:{}", orgName, user);
                        if (StringUtils.isBlank(orgName)) {
                            continue;
                        }
                        if (orgName.equals(user.getOrgName())) {
                            orgCode = user.getOrgCode();
                            if (StringUtils.isBlank(userId)) {
                                userId = user.getUserId();
                            } else {
                                userId = userId + "," + user.getUserId();
                            }
                        }
                    }
                    System.out.println("联合法制审核符合要求的orgName-----------------" + orgName);
                    nextAuditUserVo.setUserId(userId);
                    nextAuditUserVo.setIsFinal("NO");
                    nextAuditUserVo.setRealName("联合法制审核（" + orgName + "）");
                    nextAuditUserVo.setIsApprovalCenter("1");
                    nextAuditUserVo.setApprovalCenterOrgCode(orgCode);
                    nextAuditUserVo.setApprovalRoleName(flowRelation.getApprovalRoleName());
                    nextAuditUserVo.setIsCheck(Constant.STRING_0);
                    nextAuditUserVo.setApprovalRoleName("联合法制审核");
                    if (StringUtils.isNotBlank(checkCode)) {
                        if (Arrays.asList(checkCode.split(",")).contains(orgCode)) {
                            nextAuditUserVo.setIsCheck(Constant.STRING_1);
                        }
                    }
                    nextAuditUsers.add(nextAuditUserVo);
                }
                    /*if(null!=memberUserCenterVos&&memberUserCenterVos.size()>0){
                        orgCode=memberUserCenterVos.get(0).getOrgCode();
                        orgName=memberUserCenterVos.get(0).getOrgName();
                        for (MemberUserCenterVo memberUserCenterVo:memberUserCenterVos) {
                            if(StringUtils.isBlank(userId)){
                                userId = memberUserCenterVo.getUserId();
                            }else {
                                userId = userId + "," + memberUserCenterVo.getUserId();
                            }
                        }
                        nextAuditUserVo.setUserId(userId);
                        nextAuditUserVo.setIsFinal("NO");
                        nextAuditUserVo.setRealName("联合法制审核（"+orgName+"）");
                        nextAuditUserVo.setIsApprovalCenter("1");
                        nextAuditUserVo.setApprovalCenterOrgCode(orgCode);
                        nextAuditUserVo.setApprovalRoleName(flowRelation.getApprovalRoleName());
                        nextAuditUserVo.setIsCheck(Constant.STRING_0);
                        nextAuditUserVo.setApprovalRoleName("联合法制审核");
                        if(StringUtils.isNotBlank(checkCode)){
                            if(Arrays.asList(checkCode.split(",")).contains(orgCode)){
                                nextAuditUserVo.setIsCheck(Constant.STRING_1);
                            }
                        }
                        nextAuditUsers.add(nextAuditUserVo);
                    }*/

            }
        }

           /* Set<String> set = new LinkedHashSet<>();
            for (CaseUserVo user : vos) {
                System.out.println("联合法制审核过滤处理人OrgCode-----------------"+user.getOrgCode());
                if (StringUtils.isAnyBlank(user.getOrgName(),user.getOrgCode())){
                    continue;
                }
                String userAreaCode=user.getOrgCode().split("_")[0];
                System.out.println("联合法制审核过滤处理人userAreaCode-----------------"+userAreaCode);
                if(!userAreaCode.endsWith("000000")){
                    continue;
                }
                set.add(user.getOrgName());
            }
            for (String orgName : set){
                NextAuditUserVo nextAuditUserVo = new NextAuditUserVo();
                String userId="";
                String orgCode = "";
                for (CaseUserVo user : vos) {
                    log.info("orgName:{},user:{}",orgName,user);
                    if (StringUtils.isBlank(orgName)){
                        continue;
                    }
                    if(orgName.equals(user.getOrgName())){
                        orgCode = user.getOrgCode();
                        if(StringUtils.isBlank(userId)){
                            userId = user.getUserId();
                        }else {
                            userId = userId + "," + user.getUserId();
                        }
                    }
                }
                System.out.println("联合法制审核符合要求的orgName-----------------"+orgName);
                nextAuditUserVo.setUserId(userId);
                nextAuditUserVo.setIsFinal("NO");
                nextAuditUserVo.setRealName("联合法制审核（"+orgName+"）");
                nextAuditUserVo.setIsApprovalCenter("1");
                nextAuditUserVo.setApprovalCenterOrgCode(orgCode);
                nextAuditUserVo.setApprovalRoleName(flowRelation.getApprovalRoleName());
                nextAuditUserVo.setIsCheck(Constant.STRING_0);
                nextAuditUserVo.setApprovalRoleName("联合法制审核");
                if(StringUtils.isNotBlank(checkCode)){
                    if(Arrays.asList(checkCode.split(",")).contains(orgCode)){
                        nextAuditUserVo.setIsCheck(Constant.STRING_1);
                    }
                }
                nextAuditUsers.add(nextAuditUserVo);
            }*/

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @WorkFlowRollAnnotation
    public Map<String, Object> documentGeneralSubmit(String caseId, String documentCatalogCode, String userId, String opinion, String partyId, String caseAssistId, String isAutoApproval, String autoTime, String docId, String isEditApproval) {
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        //判断是否需要滚流程
        boolean isCaseSourceRoll = getIsCaseSourceRoll(caseMainInfo, documentCatalogCode);
        //判断是否需要保存日志
        boolean isSaveCaseSourceFlow = getIsSaveCaseSourceFolwLog(caseMainInfo, documentCatalogCode);
        if (isSaveCaseSourceFlow) {
            CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseMainInfo.getId());
            //设置案源流程阶段
            if (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(caseMainInfo.getCaseStatus())) {
                caseSourceRegisterMainInfo.setCaseSourceStageCode(Constant.CASE_SOURCE_STAGE_BYLASP);
            } else {
                caseSourceRegisterMainInfo.setCaseSourceStageCode(Constant.CASE_SOURCE_STAGE_LASP);
            }
            caseSourceRegisterMainInfoMapper.updateByPrimaryKeySelective(caseSourceRegisterMainInfo);
            saveCaseSourceFlow(caseSourceRegisterMainInfo, caseMainInfo);
        }
        if (caseMainInfoService.validateCaseIsInNotDealStatus(caseMainInfo, null)) {
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
            if (!caseMainInfoService.validateIsTerminateCaseWhenBreakOff(caseMainInfo, null, documentKindCode)) {
                throw new BusinessException("当前案件状态不允许进行该操作");
            }
        }
        String handleType = caseMainInfo.getHandleType();
        //更新文书记录表
        Example exampleDocRecord = new Example(CaseDocumentRecord.class);
        //特殊处理文书暂停文书,更正公示文书
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        CaseDocumentRecord caseDocumentRecord = null;
        if (StringUtils.isNotBlank(docId)) {
            caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(docId);
        }
        if (org.springframework.util.ObjectUtils.isEmpty(caseDocumentRecord)) {
            if (ObjectUtil.isNotEmpty(configBusiParamDocumentInfo)
                    && CaseStatusChangeTypeEnum.SUSPEND.getDocumentKindCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
                CaseMainInfoStatusChangeRecord changeRecord = caseMainInfoStatusChangeRecordService.getCaseMainInfoStatusChangeRecordByChangeType(caseId, CaseStatusChangeTypeEnum.SUSPEND.getCode());
                if (ObjectUtil.isNotEmpty(changeRecord)
                        && CaseStatusChangeEffectEnum.INVALID.getCode().equals(changeRecord.getStatus())) {
                    exampleDocRecord.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("id", changeRecord.getDocumentId());
                }
            } else if (StringUtils.isBlank(partyId)) {
                exampleDocRecord.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
            } else {
                exampleDocRecord.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("partyId", partyId).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
            }
            exampleDocRecord.orderBy("documentCreateTime").desc();
            List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDocRecord);
            if (caseDocumentRecords.isEmpty()) {
                throw new BusinessException("未匹配到文书记录");
            }
            caseDocumentRecord = caseDocumentRecords.get(0);
        }
        caseDocumentRecord.setDocumentAuditStatus("pending");
        caseDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.CHECKING.getCode());
        // 更新关联文书

        //updateRelationDocStatus(documentCatalogCode,"pending",caseId,partyId);
        updateRelationDocStatusByApprovalDocumentId(documentCatalogCode, "pending", caseId, partyId, caseDocumentRecord.getId());
        //查询审批关系表
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(null, documentCatalogCode);
        if (nextFlow == null || nextFlow.size() == 0) {
            throw new BusinessException("未找到下一环节关系数据!");
        }
        // 生成待审批记录
        //判断审批记录是否存在
        boolean isExist = false;
        if (ObjectUtils.isEmpty(docId)) {
            isExist = checkCaseApprovalWaitRecordIsExist(caseId, documentCatalogCode, partyId);
        } else {
            isExist = checkCaseApprovalWaitRecordIsExistByDocumentId(caseId, caseDocumentRecord.getId());
        }
        if (isExist) {
            throw new BusinessException("生成待审批记录已存在，请勿重复提交!");
        }
        CaseApprovalWaitRecord caseApprovalWaitRecord = new CaseApprovalWaitRecord();
        caseApprovalWaitRecord.setId(StringUtils.uuid());
        caseApprovalWaitRecord.setApprovalNum(nextFlow.get(0).getApprovalOrderNum());
        caseApprovalWaitRecord.setCaseId(caseId);
        caseApprovalWaitRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
        if (StringUtils.isNotBlank(nextFlow.get(0).getApprovalTerm())) {
            Integer term = nextFlow.get(0).getApprovalTerm().contains("天") ? new Integer(nextFlow.get(0).getApprovalTerm().substring(0, nextFlow.get(0).getApprovalTerm().length() - 1)) : new Integer(nextFlow.get(0).getApprovalTerm());
            caseApprovalWaitRecord.setApprovalCurrentLimitTime(term);
            caseApprovalWaitRecord.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
        }
        UserDTO userDTO = UserUtil.getUserInfo();
        caseApprovalWaitRecord.setAddUserId(userDTO.getUserId().toString());
        caseApprovalWaitRecord.setAddUserName(userDTO.getRealName());
        caseApprovalWaitRecord.setDocumentId(documentCatalogCode);
        caseApprovalWaitRecord.setFlowRelationId(nextFlow.get(0).getId());
        //标题：行政处罚的相关审批任务标题为：当事人名称+“的”+文书名称；如“张三的立案审批表”
        //CaseMainInfoVo caseMainInfoVo=caseMainInfoMapper.selectCaseMainInfo(caseId);
        String title = "";
        Example examplePd = new Example(ConfigBusiParamDocumentInfo.class);
        examplePd.createCriteria().andEqualTo("documentCatalogCode", documentCatalogCode);
        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoMapper.selectByExample(examplePd);
        if (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(caseMainInfo.getCaseStatus()) && ApiVisitDataSourceEnum.PUNISH_AY.getCode().equals(caseMainInfo.getDataSource())) {
            Example example = new Example(CaseSourcePartyInfo.class);
            example.createCriteria().andEqualTo("caseSourceId", caseMainInfo.getId()).andEqualTo("status", Constant.STRING_1);
            List<CaseSourcePartyInfo> caseSourcePartyInfos = caseSourcePartyInfoMapper.selectByExample(example);
            if (caseSourcePartyInfos != null && caseSourcePartyInfos.size() > 0) {
                CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseMainInfo.getId());
                title = caseSourceRegisterMainInfo.getPartyName() + "的" + configBusiParamDocumentInfos.get(0).getDocumentKindName();
            } else {
                title = configBusiParamDocumentInfos.get(0).getDocumentKindName();
            }

        } else {
            List<CasePartiesRecordVo> partiesRecords = casePartiesRecordService.getCasePartiesInfo(caseId);
            CasePartiesRecordVo firstPartyInfo = partiesRecords.get(Constant.INTEGER_0);
            String showPartyName = firstPartyInfo.getPartyName();
            if (partiesRecords.size() == 1) {
                title = showPartyName + "的" + configBusiParamDocumentInfos.get(0).getDocumentKindName();
            } else if (partiesRecords.size() > 1) {
                title = showPartyName + "等" + partiesRecords.size() + "个的" + configBusiParamDocumentInfos.get(0).getDocumentKindName();
            }
        }
        caseApprovalWaitRecord.setApprovalTitle(title);
        caseApprovalWaitRecord.setAddTime(new Date());
        if (StringUtils.isNotEmpty(caseAssistId)) {
            caseApprovalWaitRecord.setCaseAssistId(caseAssistId);
        }
        List<ZfPeopleBaseInfoVO> baseInfo = null;
        if (StringUtils.isBlank(userId)) {
            AuditNextUserQueryDto queryDto = new AuditNextUserQueryDto();
            queryDto.setCaseId(caseId);
            queryDto.setDocumentCatalogCode(documentCatalogCode);
            List<NextAuditUserVo> users = getNextNodeUser(queryDto);
            caseApprovalWaitRecord.setApprovalUserId(users.get(0).getUserId());
            caseApprovalWaitRecord.setApprovalUserName(users.get(0).getRealName());
        } else {
            JSONObject baseInfoRequest = new JSONObject();
            List<String> userIds = Arrays.asList(userId.split(","));
            baseInfoRequest.put("userIds", userIds);
            baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
            caseApprovalWaitRecord.setApprovalUserId(userId);
            StringJoiner stringJoiner = new StringJoiner(",");
            for (ZfPeopleBaseInfoVO vo : baseInfo) {
                stringJoiner.add(vo.getName());
            }
            caseApprovalWaitRecord.setApprovalOrgName(caseMainInfo.getCaseOrgName());
            caseApprovalWaitRecord.setApprovalUserName(stringJoiner.toString());
            caseApprovalWaitRecord.setApprovalOrgCode(caseMainInfo.getCaseOrgCode());
            caseApprovalWaitRecord.setPartyId(partyId);
        }
        caseApprovalWaitRecord.setIsAutoApproval(isAutoApproval);
        caseApprovalWaitRecord.setAutoTime(autoTime);
        caseApprovalWaitRecord.setDocId(docId);
        caseApprovalWaitRecord.setIsEditApproval(isEditApproval);
        // 生成待审批记录
        int insert = this.caseApprovalWaitRecordMapper.insert(caseApprovalWaitRecord);
        // 生成发起人完成记录，审批序号设为零。供审批日志链使用，userId设为空防止我已审批查出来
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        BeanUtils.copyProperties(caseApprovalWaitRecord, caseApprovalCompleteRecord);
        caseApprovalCompleteRecord.setId(StringUtils.uuid());
        caseApprovalCompleteRecord.setApprovalUserId("");
        caseApprovalCompleteRecord.setApprovalNum("0");
        caseApprovalCompleteRecord.setApprovalTime(new Date());
        caseApprovalCompleteRecord.setApprovalOpinion(opinion);
        caseApprovalCompleteRecord.setApprovalUserName(null);
        caseApprovalCompleteRecord.setApprovalOrgName(userDTO.getOrgName());
        caseApprovalCompleteRecord.setPartyId(partyId);
        caseApprovalCompleteRecord.setDocId(docId);
        int complete = this.caseApprovalCompleteRecordMapper.insert(caseApprovalCompleteRecord);
        int updateResult = caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);
        Boolean f = updateResult == 1 && insert == 1 && complete == 1;
        Map<String, Object> result = new HashMap<>(8);
        result.put("documentId", caseDocumentRecord.getId());
        if (f) {
            // 生成文书
            setUnderTakeOpinion(caseId, documentCatalogCode, opinion, caseDocumentRecord, userDTO, partyId, isEditApproval, docId);
            if (!isCaseSourceRoll) {
                result.put("success", "true");
                result.put("msg", "成功");
                return result;
            }
            if (!Constant.STRING_1.equals(isEditApproval)) {
                result.put("workId", caseId);
            }
            String documentLinkObjectType = configBusiParamDocumentInfos.get(0).getDocumentLinkObjectType();
            if (Constant.STRING_2.equals(handleType) && Constant.STRING_2.equals(documentLinkObjectType)) {
                result.put("workSubId", partyId);
            }
            if (!Constant.STRING_1.equals(isEditApproval)) {
                result.put("closeSignal", "CLOSE-TRIGGER-APPROVAL");
                result.put("documentCatalogCode", documentCatalogCode);
            }
            if (StringUtils.isNotBlank(caseAssistId)) {
                result.put("workAssistId", caseAssistId);
            }
           /* if(Constant.STRING_1.equals(isAutoApproval)&&Constant.STRING_3.equals(caseMainInfo.getCaseType())){
                doAutoApproval(autoTime,caseId,documentCatalogCode,caseMainInfo);
            }*/
            // 发送钉钉提醒
            //sendNewAuditDing(caseId, documentCatalogCode, caseApprovalWaitRecord.getApprovalCurrentLimitTime(), baseInfo);
            sendNewAuditDingMsg(caseId, documentCatalogCode, caseApprovalWaitRecord.getApprovalCurrentLimitTime(), Arrays.asList(userId.split(",")));
            //工作台-消息提醒
            sendNewAuditPcMsg(caseId, caseMainInfo.getCaseOrgName(), documentCatalogCode, configBusiParamDocumentInfo.getDocumentCatalogName(), caseApprovalWaitRecord, caseMainInfo.getCaseOrgCode(), Arrays.asList(userId.split(",")));
        } else {
            throw new BusinessException("文书提交审批时出现异常");
        }
        return result;
    }

    /**
     * 工作台-新审批任务提醒
     *
     * @param caseId                 案件id
     * @param handleOrgName          办案机构
     * @param documentCatalogCode    文书编码
     * @param documentCatalogName    文书名称
     * @param caseApprovalWaitRecord 案件流程实体
     * @param orgCode                用户机构编码
     * @param userIds                用户id集合
     * @author yangsizhen
     * @date 2022/12/13
     */
    private void sendNewAuditPcMsg(String caseId, String handleOrgName, String documentCatalogCode, String documentCatalogName, CaseApprovalWaitRecord caseApprovalWaitRecord, String orgCode, List<String> userIds) {
        String title = "新的审批任务提示";
        String hours = caseApprovalWaitRecord.getApprovalCurrentLimitTime() * 24 + "小时";
        String msg = "您有一份来自于" + handleOrgName + "的【" + documentCatalogName + "】待审批，审批时效" + hours + "，请前往审批任务列表查看";
        SystemMessageInsertDto dto = new SystemMessageInsertDto();
        dto.setContent(msg);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("caseId", caseId);
        paramMap.put("documentCatalogCode", documentCatalogCode);
        paramMap.put("approvalType", null);
        paramMap.put("documentType", "1");
        paramMap.put("dataSource", null);
        paramMap.put("caseAssistId", caseApprovalWaitRecord.getCaseAssistId());
        paramMap.put("partyId", caseApprovalWaitRecord.getPartyId());
        String json = JSON.toJSONString(paramMap, SerializerFeature.WRITE_MAP_NULL_FEATURES, SerializerFeature.QuoteFieldNames);
        dto.setParamsJson(json);
        dto.setReceiverDept(orgCode);
        dto.setTitle(title);
        dto.setType("1");
        for (String userId : userIds) {
            dto.setReceiverId(userId);
            caseSystemMessageService.insertSystemMessage(dto);
        }
    }

    /**
     * 工作台-审批通过提醒
     *
     * @param caseId                 案件id
     * @param documentCatalogCode    文书编码
     * @param documentCatalogName    文书名称
     * @param caseApprovalWaitRecord 案件流程实体
     * @param orgCode                用户机构编码
     * @param userIds                用户id
     * @author yangsizhen
     * @date 2022/12/13
     */
    private void sendAuditFinishPassPcMsg(String caseId, String documentCatalogCode, String documentCatalogName, CaseApprovalWaitRecord caseApprovalWaitRecord, String orgCode, List<String> userIds) {
        String title = "审批通过提示";
        String msg = "您的【" + documentCatalogName + "】审批完成，点击查看审批详情。(消息时间:" + DateUtils.getDate("yyyy-MM-dd HH:mm:ss") + ")";
        SystemMessageInsertDto dto = new SystemMessageInsertDto();
        dto.setContent(msg);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("caseId", caseId);
        paramMap.put("documentCatalogCode", documentCatalogCode);
        paramMap.put("approvalType", null);
        paramMap.put("documentType", "1");
        paramMap.put("dataSource", null);
        paramMap.put("caseAssistId", caseApprovalWaitRecord.getCaseAssistId());
        paramMap.put("partyId", caseApprovalWaitRecord.getPartyId());
        String json = JSON.toJSONString(paramMap, SerializerFeature.WRITE_MAP_NULL_FEATURES, SerializerFeature.QuoteFieldNames);
        dto.setParamsJson(json);
        dto.setReceiverDept(orgCode);
        dto.setTitle(title);
        dto.setType("2");
        for (String userId : userIds) {
            dto.setReceiverId(userId);
            caseSystemMessageService.insertSystemMessage(dto);
        }
    }

    /**
     * 工作台-审批退回提醒
     *
     * @param caseId                 案件id
     * @param documentCatalogCode    文书编码
     * @param documentCatalogName    文书名称
     * @param caseApprovalWaitRecord 案件流程实体
     * @param orgCode                用户机构编码
     * @param userIds                用户id集
     * @author yangsizhen
     * @date 2022/12/13
     */
    private void sendAuditFinishRetiredPcMsg(String caseId, String documentCatalogCode, String documentCatalogName, CaseApprovalWaitRecord caseApprovalWaitRecord, String orgCode, List<String> userIds) {
        String title = "审批退回提示";
        String msg = "您的【" + documentCatalogName + "】审批退回，点击查看审批详情。(消息时间:" + DateUtils.getDate("yyyy-MM-dd HH:mm:ss") + ")";
        SystemMessageInsertDto dto = new SystemMessageInsertDto();
        dto.setContent(msg);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("caseId", caseId);
        paramMap.put("documentCatalogCode", documentCatalogCode);
        paramMap.put("approvalType", null);
        paramMap.put("documentType", "1");
        paramMap.put("dataSource", null);
        paramMap.put("caseAssistId", caseApprovalWaitRecord.getCaseAssistId());
        paramMap.put("partyId", caseApprovalWaitRecord.getPartyId());
        String json = JSON.toJSONString(paramMap, SerializerFeature.WRITE_MAP_NULL_FEATURES, SerializerFeature.QuoteFieldNames);
        dto.setParamsJson(json);
        dto.setReceiverDept(orgCode);
        dto.setTitle(title);
        dto.setType("3");
        for (String userId : userIds) {
            dto.setReceiverId(userId);
            caseSystemMessageService.insertSystemMessage(dto);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
//    @WorkFlowRollAnnotation
    public Map<String, Object> documentGeneralSubmitWithExecute(String executeId, String documentCatalogCode, String userId, String opinion, String partyId) {
        ExecuteMainInfo executeMainInfo = executeMainInfoService.getByExecuteId(executeId);

        //判断是否需要滚流程
        //boolean isCaseSourceRoll=getIsCaseSourceRoll(caseMainInfo,documentCatalogCode);
        //保存日志
        saveExecuteFlow(executeMainInfo);

        //更新文书记录表
        Example exampleDocRecord = new Example(ExecuteDocumentRecord.class);
        exampleDocRecord.createCriteria().andEqualTo("executeId", executeId).andEqualTo("documentCatalogCode", documentCatalogCode).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        List<ExecuteDocumentRecord> executeDocumentRecords = executeDocumentRecordMapper.selectByExample(exampleDocRecord);
        if (executeDocumentRecords.isEmpty()) {
            throw new BusinessException("未匹配到文书记录");
        }
        ExecuteDocumentRecord caseDocumentRecord = executeDocumentRecords.get(0);
        caseDocumentRecord.setDocumentAuditStatus("pending");
        caseDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.CHECKING.getCode());
        // 更新关联文书
        //updateExecuteRelationDocStatus(documentCatalogCode,"pending",executeId,partyId);

        //查询审批关系表
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(null, documentCatalogCode);
        if (nextFlow == null || nextFlow.size() == 0) {
            throw new BusinessException("未找到下一环节关系数据!");
        }
        // 生成待审批记录
        //判断审批记录是否存在
        boolean isExist = checkCaseApprovalWaitRecordIsExist(executeId, documentCatalogCode, partyId);
        if (isExist) {
            throw new BusinessException("生成待审批记录已存在，请勿重复提交!");
        }
        CaseApprovalWaitRecord caseApprovalWaitRecord = new CaseApprovalWaitRecord();
        caseApprovalWaitRecord.setId(StringUtils.uuid());
        caseApprovalWaitRecord.setApprovalNum(nextFlow.get(0).getApprovalOrderNum());
        caseApprovalWaitRecord.setCaseId(executeId);
        caseApprovalWaitRecord.setApprovalType("2");//裁执分离审批
        caseApprovalWaitRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
        if (StringUtils.isNotBlank(nextFlow.get(0).getApprovalTerm())) {
            Integer term = nextFlow.get(0).getApprovalTerm().contains("天") ? new Integer(nextFlow.get(0).getApprovalTerm().substring(0, nextFlow.get(0).getApprovalTerm().length() - 1)) : new Integer(nextFlow.get(0).getApprovalTerm());
            caseApprovalWaitRecord.setApprovalCurrentLimitTime(term);
            caseApprovalWaitRecord.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
        }
        UserDTO userDTO = UserUtil.getUserInfo();
        caseApprovalWaitRecord.setAddUserId(userDTO.getUserId().toString());
        caseApprovalWaitRecord.setAddUserName(userDTO.getRealName());
        caseApprovalWaitRecord.setDocumentId(documentCatalogCode);
        caseApprovalWaitRecord.setFlowRelationId(nextFlow.get(0).getId());
        //标题：行政处罚的相关审批任务标题为：当事人名称+“的”+文书名称；如“张三的立案审批表”
        //CaseMainInfoVo caseMainInfoVo=caseMainInfoMapper.selectCaseMainInfo(caseId);
        String title = "";
        Example examplePd = new Example(ConfigBusiParamDocumentInfo.class);
        examplePd.createCriteria().andEqualTo("documentCatalogCode", documentCatalogCode);
        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoMapper.selectByExample(examplePd);

        //审批标题
        Example partiesExample = new Example(ExecutePartyInfo.class);
        partiesExample.createCriteria().andEqualTo("executeId", executeId);
        List<ExecutePartyInfo> partiesRecords = executePartyInfoMapper.selectByExample(partiesExample);
        ExecutePartyInfo firstPartyInfo = partiesRecords.get(Constant.INTEGER_0);
        String showPartyName = firstPartyInfo.getPartyName();
        if (partiesRecords.size() == 1) {
            title = showPartyName + "的" + configBusiParamDocumentInfos.get(0).getDocumentKindName();
        } else if (partiesRecords.size() > 1) {
            title = showPartyName + "等" + partiesRecords.size() + "个的" + configBusiParamDocumentInfos.get(0).getDocumentKindName();
        }
        caseApprovalWaitRecord.setApprovalTitle(title);
        caseApprovalWaitRecord.setAddTime(new Date());
        List<ZfPeopleBaseInfoVO> baseInfo = null;
        if (StringUtils.isBlank(userId)) {
            AuditNextUserQueryDto queryDto = new AuditNextUserQueryDto();
            queryDto.setCaseId(executeId);
            queryDto.setDocumentCatalogCode(documentCatalogCode);
            List<NextAuditUserVo> users = getNextNodeUser(queryDto);
            caseApprovalWaitRecord.setApprovalUserId(users.get(0).getUserId());
            caseApprovalWaitRecord.setApprovalUserName(users.get(0).getRealName());
        } else {
            JSONObject baseInfoRequest = new JSONObject();
            List<String> userIds = Arrays.asList(userId.split(","));
            baseInfoRequest.put("userIds", userIds);
            baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
            caseApprovalWaitRecord.setApprovalUserId(userId);
            StringJoiner stringJoiner = new StringJoiner(",");
            for (ZfPeopleBaseInfoVO vo : baseInfo) {
                stringJoiner.add(vo.getName());
            }
            caseApprovalWaitRecord.setApprovalOrgName(userDTO.getOrgName());
            caseApprovalWaitRecord.setApprovalUserName(stringJoiner.toString());
            caseApprovalWaitRecord.setApprovalOrgCode(userDTO.getOrgCode());
            caseApprovalWaitRecord.setPartyId(partyId);
        }
        // 生成待审批记录
        int insert = this.caseApprovalWaitRecordMapper.insert(caseApprovalWaitRecord);
        // 生成发起人完成记录，审批序号设为零。供审批日志链使用，userId设为空防止我已审批查出来
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        BeanUtils.copyProperties(caseApprovalWaitRecord, caseApprovalCompleteRecord);
        caseApprovalCompleteRecord.setId(StringUtils.uuid());
        caseApprovalCompleteRecord.setApprovalUserId("");
        caseApprovalCompleteRecord.setApprovalNum("0");
        caseApprovalCompleteRecord.setApprovalTime(new Date());
        caseApprovalCompleteRecord.setApprovalOpinion(opinion);
        caseApprovalCompleteRecord.setApprovalUserName(null);
        caseApprovalCompleteRecord.setApprovalOrgName(userDTO.getOrgName());
        caseApprovalCompleteRecord.setPartyId(partyId);
        int complete = this.caseApprovalCompleteRecordMapper.insert(caseApprovalCompleteRecord);
        int updateResult = executeDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);
        Boolean f = updateResult == 1 && insert == 1 && complete == 1;
        Map<String, Object> result = new HashMap<>(8);
        if (f) {
            // 生成文书
            //setUnderTakeOpinion(caseId, documentCatalogCode, opinion, caseDocumentRecord, userDTO,partyId);
            /*if(!isCaseSourceRoll){
                result.put("success","true");
                result.put("msg","成功");
                return result;
            }*/
            result.put("workId", executeId);
            result.put("closeSignal", "CLOSE-TRIGGER-APPROVAL");
            result.put("documentCatalogCode", documentCatalogCode);
            // 发送钉钉提醒
            sendExecuteNewAuditDing(executeId, documentCatalogCode, caseApprovalWaitRecord.getApprovalCurrentLimitTime(), baseInfo);
        } else {
            throw new BusinessException("文书提交审批时出现异常");
        }
        return result;
    }

    /**
     * 是否存日志
     *
     * @param
     * @return {@link boolean}
     * @author liyafeng
     * @date 2022/8/19
     */
    private boolean getIsSaveCaseSourceFolwLog(CaseMainInfoVo caseMainInfo, String documentCatalogCode) {
        boolean isSaveCaseSourceFolwLog = false;
        if (ApiVisitDataSourceEnum.PUNISH_AY.getCode().equals(caseMainInfo.getDataSource())) {
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            String kindCode = configBusiParamDocumentInfo.getDocumentKindCode();
            if (kindCode.equals("LASPB") || kindCode.equals("DT2BYLASPB")) {
                /*CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseMainInfo.getId());
                saveCaseSourceFlow(caseSourceRegisterMainInfo, caseMainInfo);*/
                isSaveCaseSourceFolwLog = true;
            }

        }
        return isSaveCaseSourceFolwLog;
    }

    /**
     * 是否存日志
     *
     * @param
     * @return {@link boolean}
     * @author wuzhihui
     * @date 2022/9/13
     */
    private boolean getIsSaveExecuteFolwLog(String documentCatalogCode) {
        boolean isSaveExecuteFolwLog = false;
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String kindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        if (kindCode.equals("CZFL") || kindCode.equals("DT2BYLASPB")) {
            isSaveExecuteFolwLog = true;
        }
        return isSaveExecuteFolwLog;
    }

    /**
     * 是否滚流程
     *
     * @param caseMainInfo
     * @param documentCatalogCode
     * @return {@link boolean}
     * @author liyafeng
     * @date 2022/8/19
     */
    private boolean getIsCaseSourceRoll(CaseMainInfoVo caseMainInfo, String documentCatalogCode) {
        boolean isCaseSoureRoll = true;
        //案源来源审批数据 提交审批完成后 新增流转日志
        if (ApiVisitDataSourceEnum.PUNISH_AY.getCode().equals(caseMainInfo.getDataSource())) {
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            String kindCode = configBusiParamDocumentInfo.getDocumentKindCode();
            /*if(kindCode.equals("LASPB")||kindCode.equals("DT2BYLASPB")) {
                CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseMainInfo.getId());
                saveCaseSourceFlow(caseSourceRegisterMainInfo, caseMainInfo);
            }*/
            if (kindCode.equals("DT2BYLASPB")) {
                isCaseSoureRoll = false;
            }
        }
        return isCaseSoureRoll;
    }

    /**
     * 案源立案流转日志保存
     *
     * @param caseSourceRegisterMainInfo
     * @return
     * @author liyafeng
     * @date 2022/8/18
     */
    private void saveCaseSourceFlow(CaseSourceRegisterMainInfo caseSourceRegisterMainInfo, CaseMainInfoVo caseMainInfo) {
        FlowCommonDto flowCommonDto = new FlowCommonDto();
        UserDTO userDTO = UserUtil.getUserInfo();
        flowCommonDto.setCaseSourceId(caseSourceRegisterMainInfo.getId());
        flowCommonDto.setStartPersonName(userDTO.getRealName());
        flowCommonDto.setStartPersonOrgName(userDTO.getOrgName());
        flowCommonDto.setFlowStartTime(new Date());
        flowCommonDto.setFlowEndTime(new Date());
        flowCommonDto.setStartPersonDeptName(userDTO.getDeptName());
        if (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(caseMainInfo.getCaseStatus())) {
            flowCommonDto.setFlowStageType(Constant.CASE_SOURCE_STAGE_BYLASP);
        } else {
            flowCommonDto.setFlowStageType(Constant.CASE_SOURCE_STAGE_LASP);
        }
        caseSourceFlowRecordService.saveCommonFlowRecord(flowCommonDto);
    }

    /**
     * 案源立案流转日志保存
     *
     * @param executeMainInfo
     * @return
     * @author wuzhihui
     * @date 2022/8/31
     */
    private void saveExecuteFlow(ExecuteMainInfo executeMainInfo) {
        ExecuteFlowCommonDto flowCommonDto = new ExecuteFlowCommonDto();
        UserDTO userDTO = UserUtil.getUserInfo();
        flowCommonDto.setExecuteId(executeMainInfo.getExecuteId());
        flowCommonDto.setStartPersonName(userDTO.getRealName());
        flowCommonDto.setStartPersonOrgName(userDTO.getOrgName());
        flowCommonDto.setFlowStartTime(new Date());
        flowCommonDto.setFlowEndTime(new Date());
        flowCommonDto.setStartPersonDeptName(userDTO.getDeptName());
        if (ExecuteStateEnum.ACCEPT_CASE.getCode().equals(executeMainInfo.getExecuteState())) {
            flowCommonDto.setFlowStageType(ExecuteConstant.EXECUTE_STAGE_SA);
        } else {
            flowCommonDto.setFlowStageType(ExecuteConstant.EXECUTE_STAGE_JA);
        }
        executeFlowRecordService.saveCommonFlowRecord(flowCommonDto);
    }

    /**
     * 判断待审批记录是否存在
     *
     * @param caseId
     * @param documentCatalogCode
     * @param partyId
     * @return {@link boolean}
     * @author liyafeng
     * @date 2022/7/14
     */
    private boolean checkCaseApprovalWaitRecordIsExist(String caseId, String documentCatalogCode, String partyId) {
        boolean isExist = false;
        Example example = new Example(CaseApprovalWaitRecord.class);
        if (StringUtils.isBlank(partyId)) {
            example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentId", documentCatalogCode);
        } else {
            example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentId", documentCatalogCode).andEqualTo("partyId", partyId);
        }
        List<CaseApprovalWaitRecord> caseApprovalWaitRecords = caseApprovalWaitRecordMapper.selectByExample(example);
        if (null != caseApprovalWaitRecords && caseApprovalWaitRecords.size() > 0) {
            isExist = true;
        }
        return isExist;
    }


    /**
     * 新审批 审批人钉钉消息
     *
     * @param caseId
     * @param documentCatalogCode
     * @param term
     * @param baseInfo
     */
    private void sendNewAuditDing(String caseId, String documentCatalogCode, Integer term, List<ZfPeopleBaseInfoVO> baseInfo) {
        List<CaseHandlePersonRecordVo> handlePersonRecordVos = caseHandlePersonRecordService.getCaseHandlePersonRecordListByCaseId(caseId);
        if (!handlePersonRecordVos.isEmpty()) {
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            String hours = term * 24 + "小时";
            for (ZfPeopleBaseInfoVO user : baseInfo) {
                /*if(StringUtils.isBlank(user.getDingDingId())) {
                    try {
                        String phoneNum = user.getPhone();
                        //String dingId = DingDingUtil.getAccountIdByMobile(phoneNum);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("phoneNum", phoneNum);
                        String ret=BaseUtil.post(dingIdUrl, jsonObject);
                        JSONObject retJson = JSONObject.parseObject(ret);
                        String dingId="";
                        if(Constant.STRING_200.equals(retJson.getString("code"))){
                            dingId=retJson.getString("data");
                        }
                        user.setDingDingId(dingId);
                    }catch (Exception e){
                        user.setDingDingId("");
                    }
                }*/
                if (StringUtils.isNotBlank(user.getDingDingId())) {
                    try {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("caseId", caseId);
                        jsonObject.put("documentCatalogCode", documentCatalogCode);
                        jsonObject.put("handleOrgName", handlePersonRecordVos.get(0).getHandleOrgName());
                        jsonObject.put("name", user.getName());
                        jsonObject.put("documentCatalogName", configBusiParamDocumentInfo.getDocumentCatalogName());
                        jsonObject.put("dingDingId", user.getDingDingId());
                        jsonObject.put("url", "");
                        jsonObject.put("hours", hours);
                        jsonObject.put("dingMsgType", "newAudit");
                        BaseUtil.post(dingSendUrl, jsonObject);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //DingDingUtil.newAuditMsg(caseId,documentCatalogCode,handlePersonRecordVos.get(0).getHandleOrgName(),user.getName(),configBusiParamDocumentInfo.getDocumentCatalogName(),user.getDingDingId(),hours ,"");
                }
            }
        }
    }

    /**
     * 新审批 审批人钉钉消息(裁执分离)
     *
     * @param executeId
     * @param documentCatalogCode
     * @param term
     * @param baseInfo
     */
    private void sendExecuteNewAuditDing(String executeId, String documentCatalogCode, Integer term, List<ZfPeopleBaseInfoVO> baseInfo) {
        List<ExecuteHandlePersonRecord> handlePersonRecordVos = executeHandlePersonRecordService.getExecuteHandlePersonRecordList(executeId);
        if (!handlePersonRecordVos.isEmpty()) {
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            String hours = term * 24 + "小时";
            for (ZfPeopleBaseInfoVO user : baseInfo) {
                if (StringUtils.isBlank(user.getDingDingId())) {
                    try {
                        String phoneNum = user.getPhone();
                        String dingId = DingDingUtil.getAccountIdByMobile(phoneNum);
                        user.setDingDingId(dingId);
                    } catch (Exception e) {
                        user.setDingDingId("");
                    }
                }
                if (StringUtils.isNotBlank(user.getDingDingId())) {
                    DingDingUtil.newExecuteAuditMsg(executeId, documentCatalogCode, handlePersonRecordVos.get(0).getHandleOrgName(), user.getName(), configBusiParamDocumentInfo.getDocumentCatalogName(), user.getDingDingId(), hours, "");
                }
            }
        }
    }

    /**
     * 文书添加承办人意见
     *
     * @param caseId
     * @param documentCatalogCode
     * @param opinion
     * @param caseDocumentRecord
     * @param userDTO
     */
    private void setUnderTakeOpinion(String caseId, String documentCatalogCode, String opinion, CaseDocumentRecord caseDocumentRecord, UserDTO userDTO, String partyId, String isEditApproval, String docId) {
        StageDocCommonOperateSaveDto saveDto = new StageDocCommonOperateSaveDto();
        saveDto.setCaseId(caseId);
        saveDto.setPartyId(partyId);
        saveDto.setDocumentCatalogCode(documentCatalogCode);
        JSONObject jsonObject = JSON.parseObject(caseDocumentRecord.getDocumentContent());
        HashMap<String, Object> jsonMap = new HashMap<>(16);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            jsonMap.put(entry.getKey(), entry.getValue());
        }
        String approvalStatus = DocumentStatusEnum.CHECKING.getCode();
        // 承办人意见
        jsonMap.put(OpinionType.CBR.getDocCode(), opinion);
        jsonMap.put(OpinionType.CBR.getAuditTimeCode(), LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
        String sign = iRegisterCommonService.getHandleSignData(userDTO.getUserId().toString());
        jsonMap.put(OpinionType.CBR.getAuditUserIdCode(), sign);
        saveDto.setDataMap(jsonMap);
        saveDto.setIsUpdateRelationTable(Constant.STRING_0);
        saveDto.setDocumentApprovalStatus(approvalStatus);
        saveDto.setIsEditFile(isEditApproval);
        saveDto.setDocId(docId);
        Map<String, Object> stringObjectMap = stageDocCommonOperateService.saveDocInfo(saveDto);
        String status = MapUtils.getString(stringObjectMap, "success", "");
        String tr = "true";
        if (!tr.equals(status)) {
            throw new BusinessException("文书生成失败！");
        }
    }

    private void setUnderTakeOpinionAuto(String caseId, String documentCatalogCode, String opinion, CaseDocumentRecord caseDocumentRecord, UserDTO userDTO, String partyId) {
        StageDocCommonOperateSaveDto saveDto = new StageDocCommonOperateSaveDto();
        saveDto.setCaseId(caseId);
        saveDto.setPartyId(partyId);
        saveDto.setDocumentCatalogCode(documentCatalogCode);
        JSONObject jsonObject = JSON.parseObject(caseDocumentRecord.getDocumentContent());
        HashMap<String, Object> jsonMap = new HashMap<>(16);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            jsonMap.put(entry.getKey(), entry.getValue());
        }
        String approvalStatus = DocumentStatusEnum.CHECKING.getCode();
        // 承办人意见
        jsonMap.put(OpinionType.CBR.getDocCode(), opinion);
        jsonMap.put(OpinionType.CBR.getAuditTimeCode(), LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
        String sign = iRegisterCommonService.getHandleSignData(userDTO.getUserId().toString());
        jsonMap.put(OpinionType.CBR.getAuditUserIdCode(), sign);
        saveDto.setDataMap(jsonMap);
        saveDto.setIsUpdateRelationTable(Constant.STRING_0);
        saveDto.setDocumentApprovalStatus(approvalStatus);
        Map<String, Object> stringObjectMap = stageDocCommonOperateService.saveDocInfoAuto(saveDto);
        String status = MapUtils.getString(stringObjectMap, "success", "");
        String tr = "true";
        if (!tr.equals(status)) {
            throw new BusinessException("文书生成失败！");
        }
    }

    @Override
    public List<AuditItemVo> getAuditItemList() {
        return this.caseApprovalWaitRecordMapper.getAuditItemList();
    }

    /**
     * 【V1.3.0】描述：环节撤回时，待审批数据放入审批完成表中，并标识为撤回
     *
     * @return
     * @author tianrunjia
     * @date 2022-06-24
     */
    @Override
    public void doRecallApprovalWaitRecordByCaseId(String caseId) {
        //1、将数据移入已审批记录表，并状态改为撤回
        Example queryExam = new Example(CaseApprovalWaitRecord.class);
        queryExam.createCriteria().andEqualTo("caseId", caseId);
        List<CaseApprovalWaitRecord> caseApprovalWaitRecordList = caseApprovalWaitRecordMapper.selectByExample(queryExam);
        if (caseApprovalWaitRecordList.size() > 0) {
            caseApprovalWaitRecordList.forEach(e -> {
                if (StringUtils.isBlank(e.getCaseAssistId())) {//副流程不撤回
                    if (!Constant.STRING_1.equals(e.getIsEditApproval())) {
                        this.dealApprovalWaitRecord(e);
                    }
                }
            });
        }
    }

    /**
     * 处理数据
     *
     * @param e
     */
    public void dealApprovalWaitRecord(CaseApprovalWaitRecord e) {
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        caseApprovalCompleteRecord.setId(BaseUtil.createUid());
        caseApprovalCompleteRecord.setCaseId(e.getCaseId());
        caseApprovalCompleteRecord.setApprovalOpinion("撤回");
        caseApprovalCompleteRecord.setApprovalTime(new Date());
        caseApprovalCompleteRecord.setApprovalNum(e.getApprovalNum());
        caseApprovalCompleteRecord.setApprovalUserId(e.getApprovalUserId());
        caseApprovalCompleteRecord.setApprovalOrgName(e.getApprovalOrgName());
        caseApprovalCompleteRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_RECALL);
        caseApprovalCompleteRecord.setApprovalUserName(e.getApprovalUserName());
        caseApprovalCompleteRecord.setApprovalTitle(e.getApprovalTitle());
        caseApprovalCompleteRecord.setFlowRelationId(e.getFlowRelationId());
        caseApprovalCompleteRecord.setAddTime(new Date());
        caseApprovalCompleteRecord.setAddUserId(e.getAddUserId());
        caseApprovalCompleteRecord.setAddUserName(e.getAddUserName());
        caseApprovalCompleteRecord.setDocumentId(e.getDocumentId());
        caseApprovalCompleteRecord.setPartyId(e.getPartyId());
        caseApprovalCompleteRecordMapper.insert(caseApprovalCompleteRecord);
        //2、将待审批记录删除
        Example deleteExam = new Example(CaseApprovalWaitRecord.class);
        deleteExam.createCriteria().andEqualTo("id", e.getId());
        caseApprovalWaitRecordMapper.deleteByExample(deleteExam);
    }

    /**
     * 查询下一环节配置
     *
     * @param currentRecord
     * @param docId
     * @return
     */
    private List<CaseApprovalFlowRelation> getNextCaseApprovalFlow(CaseApprovalWaitRecord currentRecord, String docId) {
        if (currentRecord != null) {
            CaseApprovalFlowRelation relation = caseDocuApprovalFolwRelationMapper.selectByPrimaryKey(currentRecord.getFlowRelationId());
            if (relation == null) {
                throw new BusinessException("系统异常，内部错误！");
            }
            Example exampleRelation = new Example(CaseApprovalFlowRelation.class);
            Integer sort = Integer.valueOf(relation.getApprovalOrderNum()) + 1;
            // 版本号条件/新增有效字段
            exampleRelation.createCriteria().andEqualTo("documentCatalogCode", relation.getDocumentCatalogCode()).andEqualTo("approvalOrderNum", sort.toString())
                    .andEqualTo("approvalFlowVerson", relation.getApprovalFlowVerson()).andEqualTo("approvalFlowId", relation.getApprovalFlowId());
            List<CaseApprovalFlowRelation> nextFlow = caseDocuApprovalFolwRelationMapper.selectByExample(exampleRelation);
            return nextFlow;
        } else {
            //处罚决定书审批表 第一次需要根据是否乡镇机构 判断是否需要走联合法制审核
            //根据文书目录编码判断类型是否为处罚决定书审批表
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(docId);
            String kindCode = configBusiParamDocumentInfo.getDocumentKindCode();
            //根据用户部门查询是否需要联合法制审核审批
            boolean centerRelationFlag = false;
            UserDTO userDTO = UserUtil.getUserInfo();
            String cfjdsspbKindCode = "CFJDSPB";
            String cfgzspbKindCode = "CFGZSPB";
            if (cfjdsspbKindCode.equals(kindCode) || cfgzspbKindCode.equals(kindCode)) {
                SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(userDTO.getOrgCode(), userDTO.getDeptCode());
                if (ObjectUtil.isNotEmpty(sysDepartParam) && "1".equals(sysDepartParam.getIsApprovalCenterUsing())) {
                    centerRelationFlag = true;
                }
            }
            if (centerRelationFlag) {
                List<CaseApprovalFlowRelation> centerApprovalRelationList = new ArrayList<>();
                Example example = new Example(CaseApprovalFlowRelation.class);
                // 版本号条件/新增有效字段
                example.createCriteria().andEqualTo("documentCatalogCode", docId).andEqualTo("isNowVersion", "1").andEqualTo("isApprovalCenter", "1");
                List<CaseApprovalFlowRelation> centerRelationList = caseDocuApprovalFolwRelationMapper.selectByExample(example);
                if (null != centerRelationList && centerRelationList.size() > 0) {
                    CaseApprovalFlowRelation centerRelation = centerRelationList.get(0);
                    Example centerRelationListExample = new Example(CaseApprovalFlowRelation.class);
                    // 版本号条件/新增有效字段
                    centerRelationListExample.createCriteria().andEqualTo("documentCatalogCode", docId).andEqualTo("isNowVersion", "1").andEqualTo("approvalFlowId", centerRelation.getApprovalFlowId());
                    centerRelationListExample.orderBy("approvalOrderNum").asc();
                    centerApprovalRelationList = caseDocuApprovalFolwRelationMapper.selectByExample(centerRelationListExample);
                }
                return centerApprovalRelationList;
            }
            Example example = new Example(CaseApprovalFlowRelation.class);
            // 版本号条件/新增有效字段
            example.createCriteria().andEqualTo("documentCatalogCode", docId).andEqualTo("isNowVersion", "1").andNotEqualTo("approvalFlowId", "4F9B01BFE80849E2A4C06C9CEDA7E83B");
            example.orderBy("approvalOrderNum").asc();
            List<CaseApprovalFlowRelation> list = caseDocuApprovalFolwRelationMapper.selectByExample(example);
            // 最新版流程没有
            if (list.isEmpty()) {
                example.clear();
                example.createCriteria().andEqualTo("documentCatalogCode", docId);
                example.orderBy("approvalFlowVerson").desc();
                example.orderBy("approvalOrderNum").asc();
                list = caseDocuApprovalFolwRelationMapper.selectByExample(example);
            }
            return list;
        }
    }

    /**
     * 查询上一环节配置
     *
     * @param currentRecord
     * @return
     */
    private List<CaseApprovalFlowRelation> getPriorCaseApprovalFlow(List<CaseApprovalWaitRecord> currentRecord) {
        CaseApprovalFlowRelation relation = caseDocuApprovalFolwRelationMapper.selectByPrimaryKey(currentRecord.get(0).getFlowRelationId());
        if (relation == null) {
            throw new BusinessException("系统异常，内部错误！");
        }
        Example exampleRelation = new Example(CaseApprovalFlowRelation.class);
        Integer sort = Integer.valueOf(relation.getApprovalOrderNum()) - 1;
        exampleRelation.createCriteria().andEqualTo("documentCatalogCode", relation.getDocumentCatalogCode()).andEqualTo("approvalOrderNum", sort.toString())
                .andEqualTo("approvalFlowVerson", relation.getApprovalFlowVerson()).andEqualTo("approvalFlowId", relation.getApprovalFlowId());
        List<CaseApprovalFlowRelation> nextFlow = caseDocuApprovalFolwRelationMapper.selectByExample(exampleRelation);
        return nextFlow;
    }

    /**
     * 根据角色查询上级用户数据
     *
     * @param baseInfoRequest
     * @return
     */
    private List<CaseUserVo> getCaseUserList(JSONObject baseInfoRequest) {
        Map<String, String> headers = HeaderUtil.headerInfo();
        String response = HttpUtil.createGet(memberUrl.concat(getCaseUserList)).addHeaders(headers).form(baseInfoRequest).execute().body();
        JSONObject info = JSONObject.parseObject(response);
        String code = "code";
        String data = "data";
        int th = 200;
        List<CaseUserVo> list = new ArrayList<>();
        if (th == info.getInteger(code)) {
            JSONArray array = info.getJSONArray(data);
            for (int i = 0; i < array.size(); i++) {
                list.add(JSON.parseObject(array.getJSONObject(i).toJSONString(), CaseUserVo.class));
            }
        }
        return list;
    }

    /**
     * 描述：获取待审批记录数
     *
     * @param caseId 案件id
     * @return int 待审批记录数
     * @author xiangyuyu
     * @date 2022-07-01 21:03
     */
    @Override
    public int getWaitToApprovalCount(String caseId) {
        CaseApprovalWaitRecord record = new CaseApprovalWaitRecord();
        record.setCaseId(caseId);
        return caseApprovalWaitRecordMapper.selectCount(record);
    }

    /**
     * 获取审批相关状态
     *
     * @param approvalQueryDto
     * @return {@link Result< ApprovalInfoVo>}
     * @author liyafeng
     * @date 2022/8/9
     */
    @Override
    public ApprovalInfoVo getApprovalInfo(ApprovalQueryDto approvalQueryDto) {
        ApprovalInfoVo vo = new ApprovalInfoVo();
        Example example = new Example(CaseApprovalWaitRecord.class);
        example.createCriteria().andEqualTo("caseId", approvalQueryDto.getCaseId()).andEqualTo("documentId", approvalQueryDto.getDocumentCatalogCode()).andLike("approvalUserId", "%" + approvalQueryDto.getApprovalUserId() + "%");
        //查询待办记录
        List<CaseApprovalWaitRecord> caseApprovalWaitRecords = caseApprovalWaitRecordMapper.selectByExample(example);
        if (null != caseApprovalWaitRecords && caseApprovalWaitRecords.size() > 0) {
            //是否存在待审批记录  0 否 1 是
            vo.setIsExistWaitApproval(Constant.STRING_1);
            //审批类型 0：待审批 1：已审批
            vo.setTaskStatus(Constant.STRING_0);
            //待审批 - 等待时间状态 0:剩余xx天；1:已到期；2:超时xx天
            Date approvalCurrentPlanendTime = caseApprovalWaitRecords.get(0).getApprovalCurrentPlanendTime();
            Date nowDate = new Date();
            if (approvalCurrentPlanendTime.compareTo(nowDate) > 0) {
                vo.setWaitStatus(Constant.STRING_0);
            } else if (approvalCurrentPlanendTime.compareTo(nowDate) == 0) {
                vo.setWaitStatus(Constant.STRING_1);
            } else if (approvalCurrentPlanendTime.compareTo(nowDate) < 0) {
                vo.setWaitStatus(Constant.STRING_2);
            }
        } else {
            //是否存在待审批记录  0 否 1 是
            vo.setIsExistWaitApproval(Constant.STRING_0);
            //审批类型 0：待审批 1：已审批
            vo.setTaskStatus(Constant.STRING_1);
            //待审批 - 等待时间状态 0:剩余xx天；1:已到期；2:超时xx天
            vo.setWaitStatus(null);
        }
        //处罚类型
        CaseMainInfoVo caseMainInfoVo = caseMainInfoService.getCaseMainInfo(approvalQueryDto.getCaseId());
        String handleType = caseMainInfoVo.getHandleType();

        Example docExample = new Example(CaseDocumentRecord.class);
        if (Constant.STRING_2.equals(handleType)) {
            docExample.createCriteria().andEqualTo("caseId", approvalQueryDto.getCaseId()).andEqualTo("documentCatalogCode", approvalQueryDto.getDocumentCatalogCode()).andEqualTo("partyId", "").andEqualTo("documentRecordStatus", Constant.STRING_1);
        } else {
            docExample.createCriteria().andEqualTo("caseId", approvalQueryDto.getCaseId()).andEqualTo("documentCatalogCode", approvalQueryDto.getDocumentCatalogCode()).andEqualTo("documentRecordStatus", Constant.STRING_1);
        }
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(docExample);
        if (null != caseDocumentRecords && caseDocumentRecords.size() > 0) {
            String pass = "pass";
            String pending = "pending";
            String rt = "return";
            CaseDocumentRecord caseDocumentRecord = caseDocumentRecords.get(0);
            //文书审核状态0:审核中；1:审核通过；2:审核退回
            if (pending.equals(caseDocumentRecord.getDocumentAuditStatus())) {
                vo.setDocumentApprovalStatus(Constant.STRING_0);
            } else if (pass.equals(caseDocumentRecord.getDocumentAuditStatus())) {
                vo.setDocumentApprovalStatus(Constant.STRING_1);
            } else if (rt.equals(caseDocumentRecord.getDocumentAuditStatus())) {
                vo.setDocumentApprovalStatus(Constant.STRING_2);
            }
        }
        return vo;
    }

    @Override
    public List getWaitAuditList(AuditQueryPageDto auditQueryPageDto) {
        PageHelper.startPage(auditQueryPageDto.getPageNum(), auditQueryPageDto.getLength());
        if (auditQueryPageDto.getLength() > 200) {
            throw new BusinessException("每页条数不能超过200");
        }
        //获取当前用户
        UserDTO userDTO = UserUtil.getUserInfo();
        auditQueryPageDto.setUserId(userDTO.getUserId().toString());
        //是否联合法制审核为空默认为0
        if (StringUtils.isBlank(auditQueryPageDto.getIsApprovalCenter())) {
            auditQueryPageDto.setIsApprovalCenter("0");
        }
        List<AuditInfoListVo> list = null;
        // 联合法制审核 查询
        String one = "1";
        if (StringUtils.isNotBlank(auditQueryPageDto.getIsApprovalCenter()) && one.equals(auditQueryPageDto.getIsApprovalCenter())) {
            list = caseApprovalWaitRecordMapper.getWaitListCenter(auditQueryPageDto);
        } else {
            list = caseApprovalWaitRecordMapper.selectWaitAuditList(auditQueryPageDto);
        }
        //处理时效
        int dfds = 0;
        for (AuditInfoListVo vo : list) {
            /*timeColor 单独查询处理
            RED("red","分红（当前日期-截止日期<0)",-1),
            ORANGE("orange","橙(当前日期-截止日期<=3)",3),
            YELLOW("yellow","黄(当前日期-截止日期<=7)",-7),
            GREEN("green","绿(当前日期-截止日期>7)",7),
            BLUE("blue","蓝(截止日期为空）",0);*/
            if (StringUtils.isNotBlank(vo.getDifferenceDays())) {
                dfds = Double.valueOf(vo.getDifferenceDays()).intValue();
                if (dfds <= 0) {
                    vo.setTimeColor("red");
                }
                if (dfds <= 1 && dfds > 0) {
                    vo.setTimeColor("yellow");
                }
                if (dfds > 1) {
                    vo.setTimeColor("blue");
                }
                //拼接时间描述
                if (dfds >= 0) {
                    vo.setDifferenceDays("剩" + dfds + "天");
                }
                if (dfds < 0) {
                    vo.setDifferenceDays("超" + (-dfds) + "天");
                }
            }
            if (StringUtils.isBlank(vo.getDeadline())) {
                vo.setTimeColor("blue");
            }
            String approvalType = vo.getApprovalType();
            String caseId = vo.getCaseId();
            // 处罚办案
            if (Constant.STRING_1.equals(approvalType)) {
                CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
                if (ObjectUtil.isNotEmpty(caseMainInfo)) {
                    vo.setCaseOrgName(caseMainInfo.getCaseOrgName());
                    vo.setCaseNumber(caseMainInfo.getCaseNumber());
                    if (StringUtils.isNotBlank(caseMainInfo.getHandleType()) && !Constant.STRING_2.equals(caseMainInfo.getHandleType())) {
                        vo.setPartyId(null);
                    }
                }
            } else {
                ExecuteMainInfo executeMainInfo = new ExecuteMainInfo();
                executeMainInfo.setExecuteId(caseId);
                ExecuteMainInfo executeMainInfo1 = executeMainInfoMapper.selectOne(executeMainInfo);
                if (ObjectUtil.isNotEmpty(executeMainInfo1)) {
                    vo.setCaseOrgName(executeMainInfo1.getExecuteOrgName());
                    vo.setCaseNumber(executeMainInfo1.getRuleNumber());
                }
            }
        }
        return list;
    }

    @Override
    public WaitPageEachColorNumVo getApprovedColorNum(AuditQueryPageDto auditQueryPageDto) {
        //获取当前用户
        UserDTO userDTO = UserUtil.getUserInfo();
        auditQueryPageDto.setUserId(userDTO.getUserId().toString());
        //是否联合法制审核为空默认为0
        if (StringUtils.isBlank(auditQueryPageDto.getIsApprovalCenter())) {
            auditQueryPageDto.setIsApprovalCenter("0");
        }
        WaitPageEachColorNumVo waitPageEachColorNumVo = null;
        // 联合法制审核 查询
        String one = "1";
        if (StringUtils.isNotBlank(auditQueryPageDto.getIsApprovalCenter()) && one.equals(auditQueryPageDto.getIsApprovalCenter())) {
            waitPageEachColorNumVo = caseApprovalWaitRecordMapper.getEachColorNumCenter(auditQueryPageDto);
        } else {
            waitPageEachColorNumVo = caseApprovalWaitRecordMapper.selectApprovedColorNum(auditQueryPageDto);
        }
        waitPageEachColorNumVo.setTotal(waitPageEachColorNumVo.getBlueNum() + waitPageEachColorNumVo.getYellowNum() + waitPageEachColorNumVo.getRedNum()
        );
        return waitPageEachColorNumVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> doAgreeAuditWithExecute(ApprovalAgreeAuditDto approvalAuditDto) {
        //读取当前用户，当前审批环节，校验角色权限，根据审批结果，流转下个节点
        // 校验审批权限 （不做了，能查到，数据存入时已校验处理）
        // 审批结果写入 case_approval_complete_record 已完成审批表 ，
        // 审批通过 写入下个节点  写入 待审批 case_approval_wait_record
        // 中间需要调用member服务 查询审批人姓名
        boolean isLast = false;
        UserDTO userDTO = UserUtil.getUserInfo();
        String partyId = approvalAuditDto.getPartyId();
        //待审核表新增下一个审批环节 数据，新增已完成审核记录。
        // 删除当前环节
        Example example = new Example(CaseApprovalWaitRecord.class);
        if (StringUtils.isBlank(partyId)) {
            example.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId());
        } else {
            example.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("partyId", partyId);
        }

        List<CaseApprovalWaitRecord> currentRecord = caseApprovalWaitRecordMapper.selectByExample(example);
        if (currentRecord.isEmpty()) {
            throw new BusinessException("当前无审批任务");
        }
        String caseId = approvalAuditDto.getCaseId();
        String documentCatalogCode = currentRecord.get(0).getDocumentId();
        ExecuteMainInfo executeMainInfo = executeMainInfoService.getByExecuteId(caseId);
        //判断是否需要滚
        //boolean isCaseSourceRoll=getIsCaseSourceRoll(caseMainInfo,documentCatalogCode);
        Map<String, Object> result = new HashMap<>(8);
        //删除待审批节点
        int del = caseApprovalWaitRecordMapper.deleteByPrimaryKey(currentRecord.get(0).getId());
        //已审批通过记录保存
        int completeIn = getCompleteInExecute(approvalAuditDto, userDTO, currentRecord);
        CaseApprovalFlowRelation caseApprovalFlowRelation = caseDocuApprovalFolwRelationMapper.selectByPrimaryKey(currentRecord.get(0).getFlowRelationId());
        if (caseApprovalFlowRelation == null) {
            throw new BusinessException("未匹配到审批流关联配置信息-flowRelationId:" + currentRecord.get(0).getFlowRelationId());
        }
        Example example1 = new Example(CaseApprovalFlowRelation.class);
        example1.createCriteria().andEqualTo("documentCatalogCode", caseApprovalFlowRelation.getDocumentCatalogCode()).andEqualTo("approvalFlowVerson", caseApprovalFlowRelation.getApprovalFlowVerson()).andEqualTo("approvalFlowId", caseApprovalFlowRelation.getApprovalFlowId());
        List<CaseApprovalFlowRelation> caseApprovalFlowRelations = caseDocuApprovalFolwRelationMapper.selectByExample(example1);

        Example exampleDocRecord = new Example(ExecuteDocumentRecord.class);
        if (StringUtils.isBlank(partyId)) {
            exampleDocRecord.createCriteria().andEqualTo("executeId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId()).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        } else {
            exampleDocRecord.createCriteria().andEqualTo("executeId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId()).andEqualTo("partyId", partyId).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        }

        List<ExecuteDocumentRecord> executeDocumentRecords = executeDocumentRecordMapper.selectByExample(exampleDocRecord);
        //是最后一个节点
        Map<String, Object> result1 = finalNodeProcessWithExecute(approvalAuditDto, currentRecord, del, completeIn, caseApprovalFlowRelations, result, executeDocumentRecords, partyId);
        if (result1 != null) {
            // 发送审批完成,提交人钉钉提醒
            sendDingAuditFinish(currentRecord, "YES");
            /*if(!isCaseSourceRoll){
                return result;
            }*/
            return result1;
        }
        //查询配置表
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(currentRecord.get(0), "");
        int sortNum = Integer.valueOf(currentRecord.get(0).getApprovalNum());
        //不是最后一个节点，下一审批人必传
        if (StringUtils.isBlank(approvalAuditDto.getNextHandler()) && caseApprovalFlowRelations.size() > sortNum) {
            throw new BusinessException("系统异常，下一环节处理人必选！");
        }
        // 下一环节待审批信息
        //判断审批记录是否存在
        boolean isExist = checkCaseApprovalWaitRecordIsExist(approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), partyId);
        if (isExist) {
            throw new BusinessException("审批通过失败，生成待审批记录已存在，请勿重复提交!");
        }
        CaseApprovalWaitRecord nextRecord = new CaseApprovalWaitRecord();
        BeanUtils.copyProperties(currentRecord.get(0), nextRecord);
        if (StringUtils.isNotBlank(nextFlow.get(0).getApprovalTerm())) {
            Integer term = nextFlow.get(0).getApprovalTerm().contains("天") ? new Integer(nextFlow.get(0).getApprovalTerm().substring(0, nextFlow.get(0).getApprovalTerm().length() - 1)) : new Integer(nextFlow.get(0).getApprovalTerm());
            nextRecord.setApprovalCurrentLimitTime(term);
            nextRecord.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
        }
        nextRecord.setId(StringUtils.uuid());
        nextRecord.setApprovalUserId(approvalAuditDto.getNextHandler());
        JSONObject baseInfoRequest = new JSONObject();
        List<String> userIds = new ArrayList<>();
        userIds.addAll(Arrays.asList(approvalAuditDto.getNextHandler().split(",")));
        baseInfoRequest.put("userIds", userIds);
        baseInfoRequest.put("orgCodes", approvalAuditDto.getApprovalCenterOrgCode());
        List<ZfPeopleBaseInfoVO> baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
        if (!baseInfo.isEmpty()) {
            StringJoiner stringJoiner = new StringJoiner(",");
            for (ZfPeopleBaseInfoVO vo : baseInfo) {
                stringJoiner.add(vo.getName());
            }
            nextRecord.setApprovalUserName(stringJoiner.toString());
        }
        nextRecord.setApprovalNum(nextFlow.get(0).getApprovalOrderNum());
        nextRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
        nextRecord.setFlowRelationId(nextFlow.get(0).getId());
        /*if (StringUtils.isNotBlank(approvalAuditDto.getApprovalCenterOrgName())){
            nextRecord.setApprovalOrgName(approvalAuditDto.getApprovalCenterOrgName());
            if (approvalAuditDto.getApprovalCenterOrgName().contains("联合法制审核")){
                String approvalCenterOrgName = approvalAuditDto.getApprovalCenterOrgName();
                approvalCenterOrgName = approvalCenterOrgName.substring(approvalCenterOrgName.indexOf("（") + 1,approvalCenterOrgName.indexOf("）"));
                nextRecord.setApprovalOrgName(approvalCenterOrgName);
            }
        }
        nextRecord.setApprovalOrgCode(approvalAuditDto.getApprovalCenterOrgCode());*/
        nextRecord.setPartyId(partyId);
        int nextIn = caseApprovalWaitRecordMapper.insert(nextRecord);
        Boolean f = (del == 1 && completeIn == 1 && nextIn == 1);
        if (f) {
            // 生成审批后文书
            String approvalStatus = DocumentStatusEnum.CHECKING.getCode();
            makeExecuteDoc(currentRecord.get(0).getFlowRelationId(), approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), executeDocumentRecords.get(0), approvalAuditDto.getOpinion(), isLast, approvalStatus, partyId);
            // 下一审批人,新审批钉钉提醒
            sendExecuteNewAuditDing(approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), nextRecord.getApprovalCurrentLimitTime(), baseInfo);
            /*if(!isCaseSourceRoll){
                result.put("success","true");
                return result;
            }*/
            result.put("caseId", approvalAuditDto.getCaseId());
            return result;
        } else {
            throw new BusinessException("审批通过数据处理时出现异常");
        }

    }

    @Override
    //@WorkFlowRollAnnotation
    public Map<String, Object> doReturnAuditWithExecute(ApprovalReturnlAuditDto approvalAuditDto) {
        ExecuteMainInfo executeMainInfo = executeMainInfoService.getByExecuteId(approvalAuditDto.getCaseId());
        //读取当前用户，当前审批环节，校验角色权限，根据审批结果，流转下个节点
        // 校验审批权限 （不做了，能查到，数据存入时已校验处理）
        // 审批结果写入 case_approval_complete_record 已完成审批表 ，
        // 审批通过 写入下个节点  写入 待审批 case_approval_wait_record
        UserDTO userDTO = UserUtil.getUserInfo();
        //删除当前节点
        Example example = new Example(CaseApprovalWaitRecord.class);
        if (StringUtils.isBlank(approvalAuditDto.getPartyId())) {
            example.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId());
        } else {
            example.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("partyId", approvalAuditDto.getPartyId());
        }

        List<CaseApprovalWaitRecord> currentRecord = caseApprovalWaitRecordMapper.selectByExample(example);
        if (currentRecord.isEmpty()) {
            throw new BusinessException("当前无审批任务");
        }
        //判断是否需要滚流程
        //boolean isCaseSourceRoll=getIsCaseSourceRoll(caseMainInfo,currentRecord.get(0).getDocumentId());
       /* if(isSaveCaseSourceFlow){
            CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseMainInfo.getId());
            saveCaseSourceFlow(caseSourceRegisterMainInfo, caseMainInfo);
        }*/
        // 退回节点 上一节点，发起人
        //退回到发起人操作
        String start = "start";
        String one = "1";
        Map<String, Object> result = new HashMap<>(8);
        // 分布式锁
        Example exampleDocRecord = new Example(ExecuteDocumentRecord.class);
        if (StringUtils.isBlank(approvalAuditDto.getPartyId())) {
            exampleDocRecord.createCriteria().andEqualTo("executeId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId()).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode()).andNotEqualTo("documentApprovalStatus", DocumentStatusEnum.CHECK_END.getCode());
        } else {
            exampleDocRecord.createCriteria().andEqualTo("executeId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId()).andEqualTo("partyId", approvalAuditDto.getPartyId()).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode()).andNotEqualTo("documentApprovalStatus", DocumentStatusEnum.CHECK_END.getCode());
        }
        List<ExecuteDocumentRecord> executeDocumentRecords = executeDocumentRecordMapper.selectByExample(exampleDocRecord);
        //删除待审批节点
        //已审批通过记录保存
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        BeanUtils.copyProperties(currentRecord.get(0), caseApprovalCompleteRecord);
        caseApprovalCompleteRecord.setId(StringUtils.uuid());
        caseApprovalCompleteRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_RETURN);
        caseApprovalCompleteRecord.setApprovalTime(new Date());
        caseApprovalCompleteRecord.setApprovalUserId(userDTO.getUserId().toString());
        caseApprovalCompleteRecord.setApprovalOpinion(approvalAuditDto.getOpinion());
        caseApprovalCompleteRecord.setApprovalUserName(userDTO.getRealName());
        caseApprovalCompleteRecord.setApprovalBackType(approvalAuditDto.getReturnNode());
        caseApprovalCompleteRecord.setApprovalOrgName(userDTO.getOrgName());
        caseApprovalCompleteRecord.setApprovalOrgCode(userDTO.getOrgCode());
        int completeIn = caseApprovalCompleteRecordMapper.insert(caseApprovalCompleteRecord);
        int del = caseApprovalWaitRecordMapper.deleteByPrimaryKey(currentRecord.get(0).getId());
        // 判断退回上一步是否发起人或退回环节为发起人
        if (start.equals(approvalAuditDto.getReturnNode()) || one.equals(currentRecord.get(0).getApprovalNum())) {
            //案源来源审批数据 提交审批完成后 新增流转日志
            //判断是否需要保存日志
            /*boolean isSaveCaseSourceFlow=getIsSaveExecuteFolwLog(currentRecord.get(0).getDocumentId());
            if(isSaveCaseSourceFlow){
                CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(approvalAuditDto.getCaseId());
                rmCaseSourceFlow(caseSourceRegisterMainInfo, caseMainInfo);
            }*/
            // 文书状态改为未提交:修改文书表状态
            if (executeDocumentRecords.isEmpty()) {
                throw new BusinessException("未匹配到文书记录-doReturnAudit");
            }
            ExecuteDocumentRecord executeDocumentRecordForUpdate = executeDocumentRecords.get(0);
            executeDocumentRecordForUpdate.setDocumentAuditStatus("return");
            executeDocumentRecordForUpdate.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_BACK.getCode());
            // 清空审批意见
            clearExecuteOpinion(executeDocumentRecordForUpdate);
            // 更新关联文书
            updateRelationExecuteDocStatus(executeDocumentRecordForUpdate.getDocumentCatalogCode(), "return", approvalAuditDto.getCaseId(), approvalAuditDto.getPartyId());
            Boolean f = del == 1 && completeIn == 1 && executeDocumentRecordMapper.updateByPrimaryKeySelective(executeDocumentRecordForUpdate) == 1;
            if (f) {
               /* if(!isCaseSourceRoll){
                    result.put("success","true");
                    result.put("msg","成功");
                    return result;
                }*/
                result.put("workId", approvalAuditDto.getCaseId());
                /*if(Constant.STRING_2.equals(handleType)){
                    result.put("workSubId", approvalAuditDto.getPartyId());
                }*/
                result.put("stepSignal", "STEP-RETURN");
                result.put("documentCatalogCode", executeDocumentRecordForUpdate.getDocumentCatalogCode());
            } else {
                throw new BusinessException("审批退回数据处理时出现异常");
            }
            // 生成文书
            // 文书审批退回 提交人钉钉提醒
            sendDingAuditFinish(currentRecord, "NO");
            return result;
        }
        // 退回上一步操作
        String prior = "prior";
        if (prior.equals(approvalAuditDto.getReturnNode())) {
            // 查询上一环节时效
            List<CaseApprovalFlowRelation> priorflows = getPriorCaseApprovalFlow(currentRecord);
            if (priorflows.isEmpty()) {
                throw new BusinessException("未匹配到上一环节审批流配置信息");
            }
            //找出上一步操作记录,插入待审批表
            // 返回上个节点查询上个节点信息
            Example exampleComplete = new Example(CaseApprovalCompleteRecord.class);
            if (StringUtils.isBlank(approvalAuditDto.getPartyId())) {
                exampleComplete.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andGreaterThan("approvalNum", "0").andEqualTo("documentId", currentRecord.get(0).getDocumentId()).andEqualTo("flowRelationId", priorflows.get(0).getId());
            } else {
                exampleComplete.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andGreaterThan("approvalNum", "0").andEqualTo("documentId", currentRecord.get(0).getDocumentId()).andEqualTo("flowRelationId", priorflows.get(0).getId()).andEqualTo("partyId", approvalAuditDto.getPartyId());
            }
            //排序查询时间倒序
            exampleComplete.orderBy("approvalTime").desc();
            List<CaseApprovalCompleteRecord> caseApprovalCompleteRecords = caseApprovalCompleteRecordMapper.selectByExample(exampleComplete);
            if (caseApprovalCompleteRecords.isEmpty()) {
                throw new BusinessException("审批完成记录为空");
            }
            //判断审批记录是否存在
            boolean isExist = checkCaseApprovalWaitRecordIsExist(approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), approvalAuditDto.getPartyId());
            if (isExist) {
                throw new BusinessException("审批退回失败，待审批记录已存在!");
            }
            CaseApprovalWaitRecord newWaitNode = new CaseApprovalWaitRecord();
            BeanUtils.copyProperties(caseApprovalCompleteRecords.get(0), newWaitNode);
            newWaitNode.setId(StringUtils.uuid());
            newWaitNode.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
            if (StringUtils.isNotBlank(priorflows.get(0).getApprovalTerm())) {
                Integer term = priorflows.get(0).getApprovalTerm().contains("天") ? new Integer(priorflows.get(0).getApprovalTerm().substring(0, priorflows.get(0).getApprovalTerm().length() - 1)) : new Integer(priorflows.get(0).getApprovalTerm());
                newWaitNode.setApprovalCurrentLimitTime(term);
                newWaitNode.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
                newWaitNode.setFlowRelationId(priorflows.get(0).getId());
            }
            int newIn = caseApprovalWaitRecordMapper.insert(newWaitNode);
            Boolean f = (newIn == 1 && del == 1 && completeIn == 1);
            if (f) {
                result.put("documentCatalogCode", "");//看不懂用来干啥的，先这样吧，头疼
            } else {
                throw new BusinessException("审批退回数据处理时出现异常");
            }
        }
        return result;
    }

    /**
     * 速结程序查询当前审批信息
     *
     * @param caseId
     * @param documentCatalogCode
     * @return {@link FastCaseApprovalInfoVo}
     * @author liyafeng
     * @date 2022/12/11
     */
    @Override
    public FastCaseApprovalInfoVo getFastCaseApprovalInfo(String caseId, String documentCatalogCode) {
        FastCaseApprovalInfoVo vo = new FastCaseApprovalInfoVo();
        Example example = new Example(CaseApprovalWaitRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId);
        List<CaseApprovalWaitRecord> caseApprovalWaitRecords = caseApprovalWaitRecordMapper.selectByExample(example);
        if (!ObjectUtils.isEmpty(caseApprovalWaitRecords)) {
            CaseApprovalWaitRecord caseApprovalWaitRecord = caseApprovalWaitRecords.get(0);
            if (Constant.STRING_1.equals(caseApprovalWaitRecord.getIsAutoApproval())) {
                CaseApprovalFlowRelation caseApprovalFlowRelation = caseApprovalFlowRelationMapper.selectByPrimaryKey(caseApprovalWaitRecord.getFlowRelationId());
                long startTime = new Date().getTime();
                long addTime = caseApprovalWaitRecord.getAddTime().getTime();
                long time = startTime - addTime;
                int autoSurplusTime = Integer.valueOf(caseApprovalWaitRecord.getAutoTime()) - (int) time / 1000;
                if (autoSurplusTime < 0) {
                    return vo;
                }
                vo.setApprovalLikeName(caseApprovalFlowRelation.getApprovalRoleName() + "审批中");
                vo.setAutoSurplusTime(String.valueOf(autoSurplusTime));
            }
        }
        return vo;
    }

    /**
     * 获取工作台统计数据
     *
     * @param dto
     * @return
     */
    @Override
    public WorkbenchStatisticsJsonVo getWorkbenchStatistics(WorkbenchStatisticsDto dto) {
        WorkbenchStatisticsVo workbenchStatistics = caseApprovalWaitRecordMapper.getWorkbenchStatistics(dto);
        if (!Objects.nonNull(workbenchStatistics)) {
            return null;
        }
        WorkbenchStatisticsJsonVo workbenchStatisticsJsonVo = new WorkbenchStatisticsJsonVo();
        workbenchStatisticsJsonVo.setCaseSituationJson(JSONObject.parseObject(workbenchStatistics.getCaseSituation()));
        workbenchStatisticsJsonVo.setCaseRegisterJson(JSONObject.parseArray(workbenchStatistics.getCaseRegister()));
        workbenchStatisticsJsonVo.setCaseLineJson(JSONObject.parseArray(workbenchStatistics.getCaseLine()));
        workbenchStatisticsJsonVo.setCaseSourceJson(JSONObject.parseArray(workbenchStatistics.getCaseSource()));
        workbenchStatisticsJsonVo.setCaseProgramJson(JSONObject.parseArray(workbenchStatistics.getCaseProgram()));
        workbenchStatisticsJsonVo.setCasePunishmentTypeJson(JSONObject.parseArray(workbenchStatistics.getCasePunishmentType()));
        workbenchStatisticsJsonVo.setCaseRuralTownJson(JSONObject.parseObject(workbenchStatistics.getCaseRuralTown()));
        workbenchStatisticsJsonVo.setCaseTrendJson(JSONObject.parseObject(workbenchStatistics.getCaseTrend()));
        return workbenchStatisticsJsonVo;
    }

    @Override
    public List<PersonalTaskVo> getPersonalTask(PersonalTaskDto personalTaskDto) {
        PageHelper.startPage(personalTaskDto.getPageNum(), personalTaskDto.getLength());
        List<PersonalTaskVo> personalTask = caseApprovalWaitRecordMapper.getPersonalTask(personalTaskDto);
        int dfds;
        for (PersonalTaskVo vo : personalTask) {
            if ("1".equals(vo.getType())) {
                if (StringUtils.isNotBlank(vo.getDifferenceDays())) {
                    dfds = Double.valueOf(vo.getDifferenceDays()).intValue();
                    if (dfds <= 0) {
                        vo.setTimeColor("red");
                    }
                    if (dfds <= 1 && dfds > 0) {
                        vo.setTimeColor("yellow");
                    }
                    if (dfds > 1) {
                        vo.setTimeColor("blue");
                    }
                    //拼接时间描述
                    if (dfds >= 0) {
                        vo.setDifferenceDays("剩" + dfds + "天");
                    }
                    if (dfds < 0) {
                        vo.setDifferenceDays("超" + (-dfds) + "天");
                    }
                }
                if (StringUtils.isBlank(vo.getDeadline())) {
                    vo.setTimeColor("blue");
                }
            }

            if ("2".equals(vo.getType())) {
                //2.计算剩余时间
                vo.setTimeColor("");
                if (vo.getCaseTimeLimit() != null && vo.getCaseVerdictEndTime() == null) {
                    int timeLimit = BaseUtil.getBetweenDays(BaseUtil.getTodayStartDate(), vo.getCaseTimeLimit());
                    handleRemainTimes(timeLimit, vo);
                    //3.红橙黄绿蓝
                    //分红（当前日期-办案期限<0)、黄(当前日期-办案期限<=7)、蓝色(当前日期-办案期限>7) 2022-10-12
                    if (timeLimit < Constant.INTEGER_0) {
                        vo.setTimeColor("red");
                    } else if (timeLimit <= Constant.INTEGER_7) {
                        vo.setTimeColor("yellow");
                    } else if (timeLimit > Constant.INTEGER_7) {
                        vo.setTimeColor("blue");
                    }
                    //暂停设置为灰色
                    if (CaseStatusEnum.SUSPEND.getCode().equals(vo.getCaseStatus())) {
                        vo.setTimeColor("gray");
                    }
                }
            }
        }
        return personalTask;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @WorkFlowRollAnnotation
    public Map<String, Object> documentGeneralSubmitAuto(String caseId, String documentCatalogCode, String userId, String opinion, String partyId, String caseAssistId, String isAutoApproval, String autoTime) {
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        String handleType = caseMainInfo.getHandleType();
        //更新文书记录表
        Example exampleDocRecord = new Example(CaseDocumentRecord.class);
        //特殊处理文书暂停文书,更正公示文书
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        if (ObjectUtil.isNotEmpty(configBusiParamDocumentInfo) && CaseStatusChangeTypeEnum.SUSPEND.getDocumentKindCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            CaseMainInfoStatusChangeRecord changeRecord = caseMainInfoStatusChangeRecordService.getCaseMainInfoStatusChangeRecordByChangeType(caseId, CaseStatusChangeTypeEnum.SUSPEND.getCode());
            if (ObjectUtil.isNotEmpty(changeRecord) && CaseStatusChangeEffectEnum.INVALID.getCode().equals(changeRecord.getStatus())) {
                exampleDocRecord.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("id", changeRecord.getDocumentId());
            }
        } else if (StringUtils.isBlank(partyId)) {
            exampleDocRecord.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        } else {
            exampleDocRecord.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("partyId", partyId).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        }
        exampleDocRecord.orderBy("documentCreateTime").desc();
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDocRecord);
        if (caseDocumentRecords.isEmpty()) {
            throw new BusinessException("未匹配到文书记录");
        }
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecords.get(0);
        caseDocumentRecord.setDocumentAuditStatus("pending");
        caseDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.CHECKING.getCode());
        // 更新关联文书
        updateRelationDocStatus(documentCatalogCode, "pending", caseId, partyId);

        //查询审批关系表
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(null, documentCatalogCode);
        if (nextFlow == null || nextFlow.size() == 0) {
            throw new BusinessException("未找到下一环节关系数据!");
        }
        // 生成待审批记录
        //判断审批记录是否存在
        boolean isExist = checkCaseApprovalWaitRecordIsExist(caseId, documentCatalogCode, partyId);
        if (isExist) {
            throw new BusinessException("生成待审批记录已存在，请勿重复提交!");
        }
        CaseApprovalWaitRecord caseApprovalWaitRecord = new CaseApprovalWaitRecord();
        caseApprovalWaitRecord.setId(StringUtils.uuid());
        caseApprovalWaitRecord.setApprovalNum(nextFlow.get(0).getApprovalOrderNum());
        caseApprovalWaitRecord.setCaseId(caseId);
        caseApprovalWaitRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
        if (StringUtils.isNotBlank(nextFlow.get(0).getApprovalTerm())) {
            Integer term = nextFlow.get(0).getApprovalTerm().contains("天") ? new Integer(nextFlow.get(0).getApprovalTerm().substring(0, nextFlow.get(0).getApprovalTerm().length() - 1)) : new Integer(nextFlow.get(0).getApprovalTerm());
            caseApprovalWaitRecord.setApprovalCurrentLimitTime(term);
            caseApprovalWaitRecord.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
        }
        UserDTO userDTO = UserUtil.getUserInfo();
        caseApprovalWaitRecord.setAddUserId(userDTO.getUserId().toString());
        caseApprovalWaitRecord.setAddUserName(userDTO.getRealName());
        caseApprovalWaitRecord.setDocumentId(documentCatalogCode);
        caseApprovalWaitRecord.setFlowRelationId(nextFlow.get(0).getId());
        //标题：行政处罚的相关审批任务标题为：当事人名称+“的”+文书名称；如“张三的立案审批表”
        //CaseMainInfoVo caseMainInfoVo=caseMainInfoMapper.selectCaseMainInfo(caseId);
        String title = "";
        Example examplePd = new Example(ConfigBusiParamDocumentInfo.class);
        examplePd.createCriteria().andEqualTo("documentCatalogCode", documentCatalogCode);
        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoMapper.selectByExample(examplePd);
        if (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(caseMainInfo.getCaseStatus()) && ApiVisitDataSourceEnum.PUNISH_AY.getCode().equals(caseMainInfo.getDataSource())) {
            Example example = new Example(CaseSourcePartyInfo.class);
            example.createCriteria().andEqualTo("caseSourceId", caseMainInfo.getId()).andEqualTo("status", Constant.STRING_1);
            List<CaseSourcePartyInfo> caseSourcePartyInfos = caseSourcePartyInfoMapper.selectByExample(example);
            if (caseSourcePartyInfos != null && caseSourcePartyInfos.size() > 0) {
                CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseMainInfo.getId());
                title = caseSourceRegisterMainInfo.getPartyName() + "的" + configBusiParamDocumentInfos.get(0).getDocumentKindName();
            } else {
                title = configBusiParamDocumentInfos.get(0).getDocumentKindName();
            }

        } else {
            List<CasePartiesRecordVo> partiesRecords = casePartiesRecordService.getCasePartiesInfo(caseId);
            CasePartiesRecordVo firstPartyInfo = partiesRecords.get(Constant.INTEGER_0);
            String showPartyName = firstPartyInfo.getPartyName();
            if (partiesRecords.size() == 1) {
                title = showPartyName + "的" + configBusiParamDocumentInfos.get(0).getDocumentKindName();
            } else if (partiesRecords.size() > 1) {
                title = showPartyName + "等" + partiesRecords.size() + "个的" + configBusiParamDocumentInfos.get(0).getDocumentKindName();
            }
        }
        caseApprovalWaitRecord.setApprovalTitle(title);
        caseApprovalWaitRecord.setAddTime(new Date());
        if (StringUtils.isNotEmpty(caseAssistId)) {
            caseApprovalWaitRecord.setCaseAssistId(caseAssistId);
        }
        List<ZfPeopleBaseInfoVO> baseInfo = null;
        if (StringUtils.isBlank(userId)) {
            AuditNextUserQueryDto queryDto = new AuditNextUserQueryDto();
            queryDto.setCaseId(caseId);
            queryDto.setDocumentCatalogCode(documentCatalogCode);
            List<NextAuditUserVo> users = getNextNodeUser(queryDto);
            caseApprovalWaitRecord.setApprovalUserId(users.get(0).getUserId());
            caseApprovalWaitRecord.setApprovalUserName(users.get(0).getRealName());
            caseApprovalWaitRecord.setApprovalOrgCode(caseMainInfo.getCaseOrgCode());
        } else {
            JSONObject baseInfoRequest = new JSONObject();
            List<String> userIds = Arrays.asList(userId.split(","));
            baseInfoRequest.put("userIds", userIds);
            baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
            caseApprovalWaitRecord.setApprovalUserId(userId);
            StringJoiner stringJoiner = new StringJoiner(",");
            for (ZfPeopleBaseInfoVO vo : baseInfo) {
                stringJoiner.add(vo.getName());
            }
            caseApprovalWaitRecord.setApprovalOrgName(caseMainInfo.getCaseOrgName());
            caseApprovalWaitRecord.setApprovalUserName(stringJoiner.toString());
            caseApprovalWaitRecord.setApprovalOrgCode(caseMainInfo.getCaseOrgCode());
            caseApprovalWaitRecord.setPartyId(partyId);
        }
        caseApprovalWaitRecord.setIsAutoApproval(isAutoApproval);
        caseApprovalWaitRecord.setAutoTime(autoTime);
        // 生成待审批记录
        int insert = this.caseApprovalWaitRecordMapper.insert(caseApprovalWaitRecord);
        // 生成发起人完成记录，审批序号设为零。供审批日志链使用，userId设为空防止我已审批查出来
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        BeanUtils.copyProperties(caseApprovalWaitRecord, caseApprovalCompleteRecord);
        caseApprovalCompleteRecord.setId(StringUtils.uuid());
        caseApprovalCompleteRecord.setApprovalUserId("");
        caseApprovalCompleteRecord.setApprovalNum("0");
        caseApprovalCompleteRecord.setApprovalTime(new Date());
        caseApprovalCompleteRecord.setApprovalOpinion(opinion);
        caseApprovalCompleteRecord.setApprovalUserName(null);
        caseApprovalCompleteRecord.setApprovalOrgName(userDTO.getOrgName());
        caseApprovalCompleteRecord.setPartyId(partyId);
        int complete = this.caseApprovalCompleteRecordMapper.insert(caseApprovalCompleteRecord);
        int updateResult = caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);
        Boolean f = updateResult == 1 && insert == 1 && complete == 1;
        Map<String, Object> result = new HashMap<>(8);
        result.put("documentId", caseDocumentRecord.getId());
        if (f) {
            // 生成文书
            setUnderTakeOpinionAuto(caseId, documentCatalogCode, opinion, caseDocumentRecord, userDTO, partyId);
            result.put("workId", caseId);
            String documentLinkObjectType = configBusiParamDocumentInfos.get(0).getDocumentLinkObjectType();
            if (Constant.STRING_2.equals(handleType) && Constant.STRING_2.equals(documentLinkObjectType)) {
                result.put("workSubId", partyId);
            }
            result.put("closeSignal", "CLOSE-TRIGGER-APPROVAL");
            result.put("documentCatalogCode", documentCatalogCode);
            if (StringUtils.isNotBlank(caseAssistId)) {
                result.put("workAssistId", caseAssistId);
            }
            /*if(Constant.STRING_1.equals(isAutoApproval)&&Constant.STRING_3.equals(caseMainInfo.getCaseType())){
                doAutoApproval(autoTime,caseId,documentCatalogCode,caseMainInfo,userDTO);
            }*/
        } else {
            throw new BusinessException("文书提交审批时出现异常");
        }
        return result;
    }

    private void handleRemainTimes(int timeLimit, PersonalTaskVo vo) {
        //办案期限
        if (timeLimit == Constant.INTEGER_0) {
            //vo.setRemainTime("已到期");
            vo.setDifferenceDays("截止日");
        } else if (timeLimit > Constant.INTEGER_0) {
            vo.setDifferenceDays("剩余" + timeLimit + "天");
        } else {
            vo.setDifferenceDays("超" + String.valueOf(timeLimit).substring(Constant.INTEGER_1) + "天");
        }

        if (CaseStatusEnum.SUSPEND.getCode().equals(vo.getCaseStatus())) {
            vo.setDifferenceDays("暂停");
        }

        if (vo.getCaseVerdictEndTime() == null) {
            return;
        }
        //裁决期限
        int verdictLimit = BaseUtil.getBetweenDays(BaseUtil.getTodayStartDate(), vo.getCaseVerdictEndTime());
        if (verdictLimit == Constant.INTEGER_0) {
            vo.setDifferenceDays("已到期");
        } else if (verdictLimit > Constant.INTEGER_0) {
            vo.setDifferenceDays("剩余" + verdictLimit + "天");
        } else {
            vo.setDifferenceDays("超" + String.valueOf(verdictLimit).substring(Constant.INTEGER_1) + "天");
        }

    }

    @Override
    public ApprovalAgreeAuditDto getApprovalAgreeAuditDto(ApprovalGeneralSubmitDto approvalGeneralSubmitDto) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(approvalGeneralSubmitDto.getCaseId());
        AuditNextUserQueryDto queryDto = new AuditNextUserQueryDto();
        queryDto.setCaseId(approvalGeneralSubmitDto.getCaseId());
        queryDto.setDocumentCatalogCode(approvalGeneralSubmitDto.getDocumentCatalogCode());
        List<NextAuditUserVo> users = getNextNodeUser(queryDto);
        Example example = new Example(CaseApprovalWaitRecord.class);
        if (StringUtils.isBlank(approvalGeneralSubmitDto.getPartyId())) {
            example.createCriteria().andEqualTo("caseId", approvalGeneralSubmitDto.getCaseId()).andEqualTo("documentId", approvalGeneralSubmitDto.getDocumentCatalogCode());
        } else {
            example.createCriteria().andEqualTo("caseId", approvalGeneralSubmitDto.getCaseId()).andEqualTo("documentId", approvalGeneralSubmitDto.getDocumentCatalogCode()).andEqualTo("partyId", approvalGeneralSubmitDto.getPartyId());
        }
        List<CaseApprovalWaitRecord> currentRecord = caseApprovalWaitRecordMapper.selectByExample(example);
        CaseApprovalFlowRelation relation = caseDocuApprovalFolwRelationMapper.selectByPrimaryKey(currentRecord.get(0).getFlowRelationId());
        NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(caseMainInfo, relation.getApprovalRole(), approvalGeneralSubmitDto.getDocumentCatalogCode());
        //需要自动审批
        ApprovalAgreeAuditDto dto = new ApprovalAgreeAuditDto();
        dto.setCaseId(approvalGeneralSubmitDto.getCaseId());
        dto.setAutoTime(vo.getAutoTime());
        dto.setIsAutoApproval(vo.getIsAutoApproval());
        dto.setNowHandler(currentRecord.get(0).getApprovalUserId());
        dto.setNextHandler(users.get(0).getUserId());
        dto.setOpinion("同意");
        dto.setApprovalCenterOrgCode(caseMainInfo.getCaseOrgCode());
        dto.setApprovalCenterOrgName(caseMainInfo.getCaseOrgName());
        return dto;
    }


    /**
     * 发送钉钉消息，没有org和hours
     *
     * @param caseId              案件ID
     * @param documentCatalogCode 文书目录
     * @param name                用户名
     * @param zwdingAccountId     政务钉钉ID
     * @param dingMsgType         消息类型：auditPass（审核通过），auditRetired（审核退回），newAudit（新的审批）
     */
    private void sendDingMsg(String caseId, String documentCatalogCode, String name, String zwdingAccountId, String dingMsgType) {
        this.sendDingMsg(caseId, documentCatalogCode, name, zwdingAccountId, dingMsgType, "", "");
    }

    /**
     * 发送钉钉消息
     *
     * @param caseId              案件ID
     * @param documentCatalogCode 文书目录
     * @param name                用户名
     * @param zwdingAccountId     政务钉钉ID
     * @param dingMsgType         消息类型：auditPass（审核通过），auditRetired（审核退回），newAudit（新的审批）
     */
    private void sendDingMsg(String caseId, String documentCatalogCode, String name, String zwdingAccountId, String dingMsgType, String handleOrgName, String hours) {
        try {
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("caseId", caseId);
            jsonObject.put("documentCatalogCode", documentCatalogCode);
            jsonObject.put("name", name);
            jsonObject.put("documentCatalogName", configBusiParamDocumentInfo.getDocumentCatalogName());
            jsonObject.put("dingDingId", zwdingAccountId);
            jsonObject.put("url", "");
            jsonObject.put("dingMsgType", dingMsgType);
            if (StrUtil.isNotEmpty(hours)) {
                jsonObject.put("hours", hours);
            }
            if (StrUtil.isNotEmpty(handleOrgName)) {
                jsonObject.put("handleOrgName", handleOrgName);
            }
            //todo 钉消息暂不发送
            BaseUtil.post(dingSendUrl, jsonObject);
        } catch (Exception e) {
            log.error("-----------发送钉钉消息失败，caseId：{}, 消息类型：{}--------------", caseId, dingMsgType, e);
        }
    }

    /***
     * 【V1.11.0】描述： 修改文书审批提交
     *
     * @author: zhengqiang
     * @date: 2023/2/24
     * @param: caseId
     * @param: documentCatalogCode
     * @param: userId
     * @param: opinion
     * @param: partyId
     * @param: caseAssistId
     * @param: documentId
     * @param: isEditApproval
     * @return {@link Map< String, Object>}
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> modifyDocumentGeneralSubmit(String caseId, String documentCatalogCode, String userId, String opinion, String partyId, String caseAssistId, String documentId, String isEditApproval) {
        if (StringUtils.isBlank(documentId)) {
            throw new BusinessException("文书id不允许为空");
        }
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        //判断是否需要滚流程
        boolean isCaseSourceRoll = getIsCaseSourceRoll(caseMainInfo, documentCatalogCode);
        /*if (caseMainInfoService.validateCaseIsInNotDealStatus(caseMainInfo, null)) {
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
            if (!caseMainInfoService.validateIsTerminateCaseWhenBreakOff(caseMainInfo, null, documentKindCode)) {
                throw new BusinessException("当前案件状态不允许进行该操作");
            }
        }*/

        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(documentId);
        if (ObjectUtils.isEmpty(caseDocumentRecord)) {
            throw new BusinessException("未匹配到文书记录");
        }
        caseDocumentRecord.setDocumentAuditStatus("pending");
        caseDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.CHECKING.getCode());
        // 更新关联文书
        //updateRelationDocStatusByApprovalDocumentId(documentCatalogCode,"pending", caseId, partyId, documentId);

        //查询审批关系表
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(null, documentCatalogCode);
        if (nextFlow == null || nextFlow.size() == 0) {
            throw new BusinessException("未找到下一环节关系数据!");
        }
        // 生成待审批记录
        //判断审批记录是否存在
        boolean isExist = checkCaseApprovalWaitRecordIsExistByDocumentId(caseId, documentId);
        if (isExist) {
            throw new BusinessException("生成待审批记录已存在，请勿重复提交!");
        }
        CaseApprovalWaitRecord caseApprovalWaitRecord = new CaseApprovalWaitRecord();
        caseApprovalWaitRecord.setId(StringUtils.uuid());
        caseApprovalWaitRecord.setApprovalNum(nextFlow.get(0).getApprovalOrderNum());
        caseApprovalWaitRecord.setCaseId(caseId);
        caseApprovalWaitRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
        if (StringUtils.isNotBlank(nextFlow.get(0).getApprovalTerm())) {
            Integer term = nextFlow.get(0).getApprovalTerm().contains("天") ? new Integer(nextFlow.get(0).getApprovalTerm().substring(0, nextFlow.get(0).getApprovalTerm().length() - 1)) : new Integer(nextFlow.get(0).getApprovalTerm());
            caseApprovalWaitRecord.setApprovalCurrentLimitTime(term);
            caseApprovalWaitRecord.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
        }
        UserDTO userDTO = UserUtil.getUserInfo();
        caseApprovalWaitRecord.setAddUserId(userDTO.getUserId().toString());
        caseApprovalWaitRecord.setAddUserName(userDTO.getRealName());
        caseApprovalWaitRecord.setDocumentId(documentCatalogCode);
        caseApprovalWaitRecord.setFlowRelationId(nextFlow.get(0).getId());
        //标题：行政处罚的相关审批任务标题为：当事人名称+“的”+文书名称；如“张三的立案审批表”
        String title = "";
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        if (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(caseMainInfo.getCaseStatus()) && ApiVisitDataSourceEnum.PUNISH_AY.getCode().equals(caseMainInfo.getDataSource())) {
            Example example = new Example(CaseSourcePartyInfo.class);
            example.createCriteria().andEqualTo("caseSourceId", caseMainInfo.getId()).andEqualTo("status", Constant.STRING_1);
            List<CaseSourcePartyInfo> caseSourcePartyInfos = caseSourcePartyInfoMapper.selectByExample(example);
            if (caseSourcePartyInfos != null && caseSourcePartyInfos.size() > 0) {
                CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseMainInfo.getId());
                title = caseSourceRegisterMainInfo.getPartyName() + "的" + configBusiParamDocumentInfo.getDocumentKindName();
            } else {
                title = configBusiParamDocumentInfo.getDocumentKindName();
            }

        } else {
            List<CasePartiesRecordVo> partiesRecords = casePartiesRecordService.getCasePartiesInfo(caseId);
            CasePartiesRecordVo firstPartyInfo = partiesRecords.get(Constant.INTEGER_0);
            String showPartyName = firstPartyInfo.getPartyName();
            if (partiesRecords.size() == 1) {
                title = showPartyName + "的" + configBusiParamDocumentInfo.getDocumentKindName();
            } else if (partiesRecords.size() > 1) {
                title = showPartyName + "等" + partiesRecords.size() + "个的" + configBusiParamDocumentInfo.getDocumentKindName();
            }
        }
        caseApprovalWaitRecord.setApprovalTitle(title + "修改申请");
        caseApprovalWaitRecord.setAddTime(new Date());
        if (StringUtils.isNotEmpty(caseAssistId)) {
            caseApprovalWaitRecord.setCaseAssistId(caseAssistId);
        }
        List<ZfPeopleBaseInfoVO> baseInfo = null;
        if (StringUtils.isBlank(userId)) {
            AuditNextUserQueryDto queryDto = new AuditNextUserQueryDto();
            queryDto.setCaseId(caseId);
            queryDto.setDocumentCatalogCode(documentCatalogCode);
            List<NextAuditUserVo> users = getNextNodeUser(queryDto);
            caseApprovalWaitRecord.setApprovalUserId(users.get(0).getUserId());
            caseApprovalWaitRecord.setApprovalUserName(users.get(0).getRealName());
        } else {
            JSONObject baseInfoRequest = new JSONObject();
            List<String> userIds = Arrays.asList(userId.split(","));
            baseInfoRequest.put("userIds", userIds);
            baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
            caseApprovalWaitRecord.setApprovalUserId(userId);
            StringJoiner stringJoiner = new StringJoiner(",");
            for (ZfPeopleBaseInfoVO vo : baseInfo) {
                stringJoiner.add(vo.getName());
            }
            caseApprovalWaitRecord.setApprovalOrgName(caseMainInfo.getCaseOrgName());
            caseApprovalWaitRecord.setApprovalUserName(stringJoiner.toString());
            caseApprovalWaitRecord.setApprovalOrgCode(caseMainInfo.getCaseOrgCode());
            caseApprovalWaitRecord.setPartyId(partyId);
        }
        caseApprovalWaitRecord.setDocId(documentId);
        caseApprovalWaitRecord.setIsEditApproval(isEditApproval);
        // 生成待审批记录
        int insert = this.caseApprovalWaitRecordMapper.insert(caseApprovalWaitRecord);
        // 生成发起人完成记录，审批序号设为零。供审批日志链使用，userId设为空防止我已审批查出来
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        BeanUtils.copyProperties(caseApprovalWaitRecord, caseApprovalCompleteRecord);
        caseApprovalCompleteRecord.setId(StringUtils.uuid());
        caseApprovalCompleteRecord.setApprovalUserId("");
        caseApprovalCompleteRecord.setApprovalNum("0");
        caseApprovalCompleteRecord.setApprovalTime(new Date());
        caseApprovalCompleteRecord.setApprovalOpinion(opinion);
        caseApprovalCompleteRecord.setApprovalUserName(null);
        caseApprovalCompleteRecord.setApprovalOrgName(userDTO.getOrgName());
        caseApprovalCompleteRecord.setPartyId(partyId);
        caseApprovalCompleteRecord.setDocId(documentId);
        caseApprovalCompleteRecord.setIsEditApproval(isEditApproval);
        int complete = this.caseApprovalCompleteRecordMapper.insert(caseApprovalCompleteRecord);
        int updateResult = caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);
        Boolean f = updateResult == 1 && insert == 1 && complete == 1;
        Map<String, Object> result = new HashMap<>(8);
        result.put("documentId", caseDocumentRecord.getId());
        if (f) {
            // 生成文书
            //setUnderTakeOpinion(caseId, documentCatalogCode, opinion, caseDocumentRecord, userDTO,partyId,isEditApproval,documentId);
            if (!isCaseSourceRoll) {
                result.put("success", "true");
                result.put("msg", "成功");
                return result;
            }
            //工作台-消息提醒
            sendNewAuditPcMsg(caseId, caseMainInfo.getCaseOrgName(), documentCatalogCode, configBusiParamDocumentInfo.getDocumentCatalogName(), caseApprovalWaitRecord, caseMainInfo.getCaseOrgCode(), Arrays.asList(userId.split(",")));
        } else {
            throw new BusinessException("文书提交审批时出现异常");
        }
        return result;
    }

    /**
     * 【V1.11.0】描述： 更新关联文书状态
     *
     * @param documentCatalogCode
     * @param approvalStatus
     * @param caseId
     * @param partyId
     * @param documentId
     */
    private void updateRelationDocStatusByApprovalDocumentId(String documentCatalogCode, String approvalStatus, String caseId, String partyId, String documentId) {
        // 查询关联文书
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        if (StringUtils.isNotBlank(configBusiParamDocumentInfo.getRelationDocumentCatalogCode())) {
            String fg = ",";
            String[] relationDocs = configBusiParamDocumentInfo.getRelationDocumentCatalogCode().split(fg);
            for (int i = 0; i < relationDocs.length; i++) {
                Example example = new Example(CaseDocumentRecord.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", relationDocs[i]).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode()).andNotEqualTo("documentApprovalStatus", DocumentStatusEnum.CHECK_END.getCode());
                if (StringUtils.isNotBlank(partyId)) {
                    criteria.andEqualTo("partyId", partyId);
                }
                //补正更正文书处理
                if (DocumentKindEnum.DOC_KIND_DK1BZGZSPB.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())
                        && StringUtils.isNotBlank(documentId)) {
                    criteria.andEqualTo("relationApprovalDocumentId", documentId);
                }

                List<CaseDocumentRecord> updateRecord = caseDocumentRecordMapper.selectByExample(example);

                if (!updateRecord.isEmpty()) {
                    CaseDocumentRecord record = updateRecord.get(0);
                    record.setDocumentAuditStatus(approvalStatus);
                    String pass = "pass";
                    String pending = "pending";
                    String rt = "return";
                    // 状态判断更新
                    if (pass.equals(approvalStatus)) {
                        record.setDocumentApprovalTime(LocalDateTime.now());
                        record.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_END.getCode());
                    }
                    if (pending.equals(approvalStatus)) {
                        record.setDocumentApprovalStatus(DocumentStatusEnum.CHECKING.getCode());
                    }
                    if (rt.equals(approvalStatus)) {
                        record.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_BACK.getCode());
                    }
                    caseDocumentRecordMapper.updateByPrimaryKeySelective(record);
                }
            }
        }
    }

    /**
     * 【V1.11.0】描述： 判断待审批记录是否存在
     *
     * @param caseId
     * @param documentId
     * @return {@link boolean}
     */
    private boolean checkCaseApprovalWaitRecordIsExistByDocumentId(String caseId, String documentId) {
        boolean isExist = false;
        Example example = new Example(CaseApprovalWaitRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("docId", documentId);
        List<CaseApprovalWaitRecord> caseApprovalWaitRecords = caseApprovalWaitRecordMapper.selectByExample(example);
        if (null != caseApprovalWaitRecords && caseApprovalWaitRecords.size() > 0) {
            isExist = true;
        }
        return isExist;
    }


    /**
     * 【V1.11.0】描述： 审批通过(文书修改审批)
     *
     * @return {@link Map< String, Object>}
     * @author: zhengqiang
     * @date: 2023/2/24
     * @param: approvalAuditDto
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> doAgreeAuditOfModifyRecord(ApprovalAgreeAuditDto approvalAuditDto) {
        //读取当前用户，获取当前审批环节
        UserDTO userDTO = UserUtil.getUserInfo();
        String partyId = approvalAuditDto.getPartyId();
        String docId = approvalAuditDto.getDocId();
        List<CaseApprovalWaitRecord> currentRecord = null;
        if (StringUtils.isNotBlank(docId)) {
            Example waitExample = new Example(CaseApprovalWaitRecord.class);
            waitExample.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("docId", docId);
            currentRecord = caseApprovalWaitRecordMapper.selectByExample(waitExample);
        }
        //如果待审批记录不存在 则提示无审批记录
        if (ObjectUtils.isEmpty(currentRecord)) {
            throw new BusinessException("当前无审批任务");
        }

        //查询文书记录
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(docId);
        if (ObjectUtils.isEmpty(caseDocumentRecord)) {
            throw new BusinessException("审批文书不存在");
        }

        //校验登录人的id是否为审批人
        String userId = userDTO.getUserId().toString();
        if (!currentRecord.get(0).getApprovalUserId().contains(userId)) {
            throw new BusinessException("当前待审批记录，已被其他人审批，请刷新当前页面！");
        }
        //删除待审批节点
        int del = caseApprovalWaitRecordMapper.deleteByPrimaryKey(currentRecord.get(0).getId());
        //查询案件信息
        String caseId = approvalAuditDto.getCaseId();
        CaseMainInfoVo caseMainInfo = caseMainInfoMapper.selectCaseMainInfo(caseId);
        //判断是否需要滚流程
        String documentCatalogCode = currentRecord.get(0).getDocumentId();
        Map<String, Object> result = new HashMap<>(8);
        //已审批通过记录保存
        int completeIn = getCompleteIn(approvalAuditDto, currentRecord);
        //获取审批relation
        CaseApprovalFlowRelation caseApprovalFlowRelation = caseDocuApprovalFolwRelationMapper.selectByPrimaryKey(currentRecord.get(0).getFlowRelationId());
        if (caseApprovalFlowRelation == null) {
            throw new BusinessException("未匹配到审批流关联配置信息-flowRelationId:" + currentRecord.get(0).getFlowRelationId());
        }
        Example example1 = new Example(CaseApprovalFlowRelation.class);
        example1.createCriteria().andEqualTo("documentCatalogCode", caseApprovalFlowRelation.getDocumentCatalogCode()).andEqualTo("approvalFlowVerson", caseApprovalFlowRelation.getApprovalFlowVerson()).andEqualTo("approvalFlowId", caseApprovalFlowRelation.getApprovalFlowId());
        List<CaseApprovalFlowRelation> caseApprovalFlowRelations = caseDocuApprovalFolwRelationMapper.selectByExample(example1);
        //是最后一个节点
        Map<String, Object> result1 = finalNodeProcessOfModifyDocument(approvalAuditDto, currentRecord, del, completeIn, caseApprovalFlowRelations, result, caseDocumentRecord);
        if (result1 != null) {
            // 发送审批完成,提交人钉钉提醒
            sendDingAuditFinishMsg(currentRecord, "YES");

            //工作台-消息提醒
            List<String> userIds = new ArrayList<>();
            userIds.add(currentRecord.get(0).getAddUserId());
            ConfigBusiParamDocumentInfo catalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            sendAuditFinishPassPcMsg(caseId, documentCatalogCode, catalogCode.getDocumentCatalogName(), currentRecord.get(0), caseMainInfo.getCaseOrgCode(), userIds);
            return result1;
        }
        //查询配置表
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(currentRecord.get(0), "");
        int sortNum = Integer.valueOf(currentRecord.get(0).getApprovalNum());
        //不是最后一个节点，下一审批人必传
        if (StringUtils.isBlank(approvalAuditDto.getNextHandler()) && caseApprovalFlowRelations.size() > sortNum) {
            throw new BusinessException("系统异常，下一环节处理人必选！");
        }
        // 下一环节待审批信息
        //判断审批记录是否存在
        boolean isExist = checkCaseApprovalWaitRecordIsExistByDocumentId(caseId, caseDocumentRecord.getId());
        if (isExist) {
            throw new BusinessException("审批通过失败，生成待审批记录已存在，请勿重复提交!");
        }
        CaseApprovalWaitRecord nextRecord = new CaseApprovalWaitRecord();
        BeanUtils.copyProperties(currentRecord.get(0), nextRecord);
        if (StringUtils.isNotBlank(nextFlow.get(0).getApprovalTerm())) {
            Integer term = nextFlow.get(0).getApprovalTerm().contains("天") ? new Integer(nextFlow.get(0).getApprovalTerm().substring(0, nextFlow.get(0).getApprovalTerm().length() - 1)) : new Integer(nextFlow.get(0).getApprovalTerm());
            nextRecord.setApprovalCurrentLimitTime(term);
            nextRecord.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
        }
        nextRecord.setId(StringUtils.uuid());
        JSONObject baseInfoRequest = new JSONObject();
        if (StringUtils.isBlank(approvalAuditDto.getNextHandler())) {
            CaseMainInfo mainInfo = new CaseMainInfo();
            BeanUtils.copyProperties(caseMainInfo, mainInfo);
            NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(mainInfo, nextFlow.get(0).getApprovalRole(), documentCatalogCode);
            nextRecord.setApprovalUserId(vo.getUserId());
            approvalAuditDto.setNextHandler(vo.getUserId());
            approvalAuditDto.setAutoTime(vo.getAutoTime());
            approvalAuditDto.setIsAutoApproval(vo.getIsAutoApproval());
        } else {
            nextRecord.setApprovalUserId(approvalAuditDto.getNextHandler());
            if (Constant.STRING_1.equals(approvalAuditDto.getIsAutoApproval())) {
                CaseMainInfo mainInfo = new CaseMainInfo();
                BeanUtils.copyProperties(caseMainInfo, mainInfo);
                NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(mainInfo, nextFlow.get(0).getApprovalRole(), documentCatalogCode);
                approvalAuditDto.setNextHandler(vo.getUserId());
                approvalAuditDto.setAutoTime(vo.getAutoTime());
                approvalAuditDto.setIsAutoApproval(vo.getIsAutoApproval());
            }
        }
        List<String> userIds = new ArrayList<>();
        userIds.addAll(Arrays.asList(approvalAuditDto.getNextHandler().split(",")));
        baseInfoRequest.put("userIds", userIds);
        if (StringUtils.isNotBlank(approvalAuditDto.getApprovalCenterOrgCode())) {
            List<String> orgCodes = new ArrayList<>();
            orgCodes.add(approvalAuditDto.getApprovalCenterOrgCode());
            baseInfoRequest.put("orgCodes", orgCodes);
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userIds", userIds);
        if (null != userIds && userIds.size() > 0) {
            List<String> userNameList = memberUserSignMapper.selectUserNameList(paramMap);
            if (null != userNameList && userNameList.size() > 0) {
                StringJoiner stringJoiner = new StringJoiner(",");
                for (String userName : userNameList) {
                    stringJoiner.add(userName);
                }
                nextRecord.setApprovalUserName(stringJoiner.toString());
            } else {
                nextRecord.setApprovalUserName("");
            }
        } else {
            nextRecord.setApprovalUserName("");
        }
        nextRecord.setApprovalNum(nextFlow.get(0).getApprovalOrderNum());
        nextRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
        nextRecord.setFlowRelationId(nextFlow.get(0).getId());
        if (StringUtils.isNotBlank(approvalAuditDto.getApprovalCenterOrgName())) {
            nextRecord.setApprovalOrgName(approvalAuditDto.getApprovalCenterOrgName());
            if (approvalAuditDto.getApprovalCenterOrgName().contains("联合法制审核")) {
                String approvalCenterOrgName = approvalAuditDto.getApprovalCenterOrgName();
                approvalCenterOrgName = approvalCenterOrgName.substring(approvalCenterOrgName.indexOf("（") + 1, approvalCenterOrgName.indexOf("）"));
                nextRecord.setApprovalOrgName(approvalCenterOrgName);
                nextRecord.setApprovalOrgCode(approvalAuditDto.getApprovalCenterOrgCode());
            }
        } else {
            nextRecord.setApprovalOrgCode(caseMainInfo.getCaseOrgCode());
        }
        nextRecord.setPartyId(partyId);
        nextRecord.setAutoTime(approvalAuditDto.getAutoTime());
        nextRecord.setIsAutoApproval(approvalAuditDto.getIsAutoApproval());
        nextRecord.setDocId(docId);
        int nextIn = caseApprovalWaitRecordMapper.insert(nextRecord);
        Boolean f = (del == 1 && completeIn == 1 && nextIn == 1);
        if (f) {
            // 生成审批后文书
            //String approvalStatus = DocumentStatusEnum.CHECKING.getCode();
            //makeDoc(currentRecord.get(0).getFlowRelationId(), approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), caseDocumentRecord, approvalAuditDto.getOpinion(), isLast, approvalStatus,partyId,approvalAuditDto.getCaseAssistId(),currentRecord.get(0).getIsEditApproval(),currentRecord.get(0).getDocId());
            // 下一审批人,新审批钉钉提醒
            sendNewAuditDingMsg(approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), nextRecord.getApprovalCurrentLimitTime(), userIds);

            //工作台-消息提醒
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
            sendNewAuditPcMsg(caseId, caseMainInfo.getCaseOrgName(), documentCatalogCode, configBusiParamDocumentInfo.getDocumentCatalogName(), nextRecord, caseMainInfo.getCaseOrgCode(), userIds);

            result.put("caseId", approvalAuditDto.getCaseId());
            return result;
        } else {
            throw new BusinessException("审批通过数据处理时出现异常");
        }

    }

    /**
     * 合并提交审批接口，该文书需要审批调用（简案快办合并提交使用）
     *
     * @param dto
     * @return {@link Map< String, Object>}
     * @author liyafeng
     * @date 2023/4/24
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public Map<String, Object> documentGeneralSubmitMergeAuto(ApprovalGeneralSubmitDto dto) {
        UserDTO userDTO = UserUtil.getUserInfo();
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(dto.getCaseId());
        //查询审批关系表
        String documentCode = dto.getDocumentCatalogCode();
        if (Constant.STRING_1.equals(dto.getIsMerge())) {
            CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(dto.getCaseId());
            documentCode = getMergeDocumentCatalogCode(caseMainDetailInfo.getInvestConclusion());
        }
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(null, documentCode);
        if (nextFlow == null || nextFlow.size() == 0) {
            throw new BusinessException("未找到下一环节关系数据!");
        }
        // 生成待审批记录
        CaseApprovalWaitRecord caseApprovalWaitRecord = saveCaseApprovalWaitRecordMerge(caseMainInfo, documentCode, dto, nextFlow);
        //初始化完成审批记录
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = SaveCaseApprovalCompleteRecordMerge(caseApprovalWaitRecord, dto);
        //合并审批需要拆分文书目录编码
        String[] documentCatalogCodeArr = dto.getDocumentCatalogCode().split(Constant.STRING_COMMA);
        if (ObjectUtils.isEmpty(documentCatalogCodeArr)) {
            throw new BusinessException("文书目录编码传参异常");
        }
        List<String> documentCatalogCodeList = Arrays.asList(documentCatalogCodeArr);
        for (String documentCatalogCode : documentCatalogCodeList) {
            //更新文书记录表
            CaseDocumentRecord caseDocumentRecord = modifyCaseDocumentRecordApprovalStatus(documentCatalogCode, dto);
            // 更新关联文书
            updateRelationDocStatus(documentCatalogCode, "pending", dto.getCaseId(), dto.getPartyId());
            // 生成文书
            if (ObjectUtils.isNotEmpty(caseDocumentRecord) && ObjectUtils.isNotEmpty(caseApprovalWaitRecord)) {
                ConfigBusiParamDocumentInfo configBusiParamDocumentInfo
                        = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
                String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
                String opinion = dto.getOpinion();
                if (DocumentKindEnum.DOC_KIND_CFGZSPB.getCode().equals(documentKindCode)) {
                    opinion = dto.getInformOpinion();
                }
                setUnderTakeOpinionMergeAuto(dto.getCaseId(), documentCatalogCode, opinion, caseDocumentRecord, userDTO, dto.getPartyId());
            }
        }
        Map<String, Object> result = new HashMap<>(8);
        result.put("closeSignal", "CLOSE-TRIGGER-APPROVAL");
        /*if (f) {
            // 生成文书
            setUnderTakeOpinionAuto(caseId, documentCatalogCode, opinion, caseDocumentRecord, userDTO,partyId);
            result.put("workId", caseId);
            String documentLinkObjectType = configBusiParamDocumentInfos.get(0).getDocumentLinkObjectType();
            if(Constant.STRING_2.equals(handleType) &&  Constant.STRING_2.equals(documentLinkObjectType)){
                result.put("workSubId", partyId);
            }

            result.put("documentCatalogCode", documentCatalogCode);
            if(StringUtils.isNotBlank(caseAssistId)){
                result.put("workAssistId", caseAssistId);
            }
            *//*if(Constant.STRING_1.equals(isAutoApproval)&&Constant.STRING_3.equals(caseMainInfo.getCaseType())){
                doAutoApproval(autoTime,caseId,documentCatalogCode,caseMainInfo,userDTO);
            }*//*
        } else {
            throw new BusinessException("文书提交审批时出现异常");
        }*/
        return result;
    }

    private void setUnderTakeOpinionMergeAuto(String caseId, String documentCatalogCode, String opinion, CaseDocumentRecord caseDocumentRecord, UserDTO userDTO, String partyId) {
        StageDocCommonOperateSaveDto saveDto = new StageDocCommonOperateSaveDto();
        saveDto.setCaseId(caseId);
        saveDto.setPartyId(partyId);
        saveDto.setDocumentCatalogCode(documentCatalogCode);
        JSONObject jsonObject = JSON.parseObject(caseDocumentRecord.getDocumentContent());
        HashMap<String, Object> jsonMap = new HashMap<>(16);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            jsonMap.put(entry.getKey(), entry.getValue());
        }
        String approvalStatus = DocumentStatusEnum.CHECKING.getCode();
        // 承办人意见
        jsonMap.put(OpinionType.CBR.getDocCode(), opinion);
        jsonMap.put(OpinionType.CBR.getAuditTimeCode(), LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
        String sign = iRegisterCommonService.getHandleSignData(userDTO.getUserId().toString());
        jsonMap.put(OpinionType.CBR.getAuditUserIdCode(), sign);
        saveDto.setDataMap(jsonMap);
        saveDto.setIsUpdateRelationTable(Constant.STRING_0);
        saveDto.setDocumentApprovalStatus(approvalStatus);
        saveDto.setCloseSignal("CLOSE-TRIGGER-APPROVAL");
        Map<String, Object> stringObjectMap = stageDocCommonOperateService.saveDocInfoAuto(saveDto);
        String status = MapUtils.getString(stringObjectMap, "success", "");
        String tr = "true";
        if (!tr.equals(status)) {
            throw new BusinessException("文书生成失败！");
        }
    }

    /**
     * 获取审批通过dto(合并提交)
     *
     * @param approvalGeneralSubmitDto
     * @return {@link ApprovalAgreeAuditDto}
     * @author liyafeng
     * @date 2023/4/24
     */
    @Override
    public ApprovalAgreeAuditDto getApprovalAgreeAuditMergeDto(ApprovalGeneralSubmitDto approvalGeneralSubmitDto) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(approvalGeneralSubmitDto.getCaseId());
        AuditNextUserQueryDto queryDto = new AuditNextUserQueryDto();
        queryDto.setCaseId(approvalGeneralSubmitDto.getCaseId());
        queryDto.setDocumentCatalogCode(approvalGeneralSubmitDto.getDocumentCatalogCode());
        List<NextAuditUserVo> users = getNextNodeUserMerge(queryDto);
        Example example = new Example(CaseApprovalWaitRecord.class);
        //文书目录编码先写死
        //String documentCatalogCode="DC1A0223300CFGZSPB000000001";
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(approvalGeneralSubmitDto.getCaseId());
        String documentCatalogCode = getMergeDocumentCatalogCode(caseMainDetailInfo.getInvestConclusion());
        if (StringUtils.isBlank(approvalGeneralSubmitDto.getPartyId())) {
            example.createCriteria().andEqualTo("caseId", approvalGeneralSubmitDto.getCaseId()).andEqualTo("documentId", approvalGeneralSubmitDto.getDocumentCatalogCode());
        } else {
            example.createCriteria().andEqualTo("caseId", approvalGeneralSubmitDto.getCaseId()).andEqualTo("documentId", approvalGeneralSubmitDto.getDocumentCatalogCode()).andEqualTo("partyId", approvalGeneralSubmitDto.getPartyId());
        }
        List<CaseApprovalWaitRecord> currentRecord = caseApprovalWaitRecordMapper.selectByExample(example);
        CaseApprovalFlowRelation relation = caseDocuApprovalFolwRelationMapper.selectByPrimaryKey(currentRecord.get(0).getFlowRelationId());
        NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(caseMainInfo, relation.getApprovalRole(), documentCatalogCode);
        //需要自动审批
        ApprovalAgreeAuditDto dto = new ApprovalAgreeAuditDto();
        dto.setCaseId(approvalGeneralSubmitDto.getCaseId());
        dto.setAutoTime(vo.getAutoTime());
        dto.setIsAutoApproval(vo.getIsAutoApproval());
        dto.setNowHandler(currentRecord.get(0).getApprovalUserId());
        dto.setNextHandler(users.get(0).getUserId());
        dto.setOpinion("同意");
        dto.setApprovalCenterOrgCode(caseMainInfo.getCaseOrgCode());
        dto.setApprovalCenterOrgName(caseMainInfo.getCaseOrgName());
        return dto;
    }

    /**
     * 自动审批通过
     *
     * @param approvalAuditDto
     * @return {@link Map< String, Object>}
     * @author liyafeng
     * @date 2023/4/25
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public Map<String, Object> doAgreeAuditMergeAuto(ApprovalAgreeAuditDto approvalAuditDto) {
        //默认不是最后最后审批节点
        boolean isLast = false;
        //读取当前用户，获取当前审批环节
        String partyId = approvalAuditDto.getPartyId();
        Example example = new Example(CaseApprovalWaitRecord.class);
        if (StringUtils.isBlank(partyId)) {
            example.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentId", approvalAuditDto.getDocumentCatalogCode());
        } else {
            example.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("partyId", partyId).andEqualTo("documentId", approvalAuditDto.getDocumentCatalogCode());
        }
        List<CaseApprovalWaitRecord> currentRecord = caseApprovalWaitRecordMapper.selectByExample(example);
        //如果待审批记录不存在 则提示无审批记录
        if (currentRecord.isEmpty()) {
            throw new BusinessException("当前无审批任务");
        }
        //删除待审批节点
        int del = caseApprovalWaitRecordMapper.deleteByPrimaryKey(currentRecord.get(0).getId());
        //查询案件信息
        String caseId = approvalAuditDto.getCaseId();
        CaseMainInfoVo caseMainInfo = caseMainInfoMapper.selectCaseMainInfo(caseId);
        //判断是否需要滚流程
        //String documentCatalogCode=currentRecord.get(0).getDocumentId();
        Map<String, Object> result = new HashMap<>(8);
        //已审批通过记录保存
        int completeIn = getCompleteInAuto(approvalAuditDto, currentRecord);
        //获取审批relation
        CaseApprovalFlowRelation caseApprovalFlowRelation = caseDocuApprovalFolwRelationMapper.selectByPrimaryKey(currentRecord.get(0).getFlowRelationId());
        if (caseApprovalFlowRelation == null) {
            throw new BusinessException("未匹配到审批流关联配置信息-flowRelationId:" + currentRecord.get(0).getFlowRelationId());
        }
        Example example1 = new Example(CaseApprovalFlowRelation.class);
        example1.createCriteria().andEqualTo("documentCatalogCode", caseApprovalFlowRelation.getDocumentCatalogCode()).andEqualTo("approvalFlowVerson", caseApprovalFlowRelation.getApprovalFlowVerson()).andEqualTo("approvalFlowId", caseApprovalFlowRelation.getApprovalFlowId());
        List<CaseApprovalFlowRelation> caseApprovalFlowRelations = caseDocuApprovalFolwRelationMapper.selectByExample(example1);
        //合并审批需要拆分文书目录编码
        String[] documentCatalogCodeArr = approvalAuditDto.getDocumentCatalogCode().split(Constant.STRING_COMMA);
        if (ObjectUtils.isEmpty(documentCatalogCodeArr)) {
            throw new BusinessException("文书目录编码传参异常");
        }
        List<String> documentCatalogCodeList = Arrays.asList(documentCatalogCodeArr);
        for (String documentCatalogCode : documentCatalogCodeList) {

            //获取文书记录
            Example exampleDocRecord = new Example(CaseDocumentRecord.class);
            if (StringUtils.isBlank(partyId)) {
                exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", documentCatalogCode).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
            } else {
                exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("partyId", partyId).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
            }
            List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDocRecord);
            //是最后一个节点
            Map<String, Object> result1 = finalNodeProcessMergeAuto(approvalAuditDto, currentRecord, del, completeIn, caseApprovalFlowRelations, result, caseDocumentRecords, partyId, approvalAuditDto.getCaseAssistId(), documentCatalogCode);
            String closeSignal = MapUtils.getString(result1, "closeSignal", "");
            if ("CLOSE-TRIGGER-APPROVAL-PASS".equals(closeSignal)) {
                // 发送审批完成,提交人钉钉提醒
                //sendDingAuditFinish(currentRecord,"YES");
                //sendDingAuditFinishMsg(currentRecord,"YES");
                return result1;
            }
            if (result1 != null) {
                // 发送审批完成,提交人钉钉提醒
                //sendDingAuditFinish(currentRecord,"YES");
                if (SpringContextUtil.checkIsPrdProfile()) {
                    sendDingAuditFinishMsg(currentRecord, "YES");
                }
                continue;
            }
            // 生成审批后文书
            String approvalStatus = DocumentStatusEnum.CHECKING.getCode();
            makeDocAuto(currentRecord.get(0).getFlowRelationId(), approvalAuditDto.getCaseId(), documentCatalogCode, caseDocumentRecords.get(0), approvalAuditDto.getOpinion(), isLast, approvalStatus, partyId, approvalAuditDto.getCaseAssistId(), approvalAuditDto.getNowHandler());
            result.put("caseId", approvalAuditDto.getCaseId());
        }
        //查询配置表
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(currentRecord.get(0), "");
        int sortNum = Integer.valueOf(currentRecord.get(0).getApprovalNum());
        //不是最后一个节点，下一审批人必传
        if (StringUtils.isBlank(approvalAuditDto.getNextHandler()) && caseApprovalFlowRelations.size() > sortNum) {
            throw new BusinessException("系统异常，下一环节处理人必选！");
        }
        // 下一环节待审批信息
        //判断审批记录是否存在
        boolean isExist = checkCaseApprovalWaitRecordIsExist(approvalAuditDto.getCaseId(), currentRecord.get(0).getDocumentId(), partyId);
        if (isExist) {
            throw new BusinessException("审批通过失败，生成待审批记录已存在，请勿重复提交!");
        }
        CaseApprovalWaitRecord nextRecord = new CaseApprovalWaitRecord();
        BeanUtils.copyProperties(currentRecord.get(0), nextRecord);
        if (StringUtils.isNotBlank(nextFlow.get(0).getApprovalTerm())) {
            Integer term = nextFlow.get(0).getApprovalTerm().contains("天") ? new Integer(nextFlow.get(0).getApprovalTerm().substring(0, nextFlow.get(0).getApprovalTerm().length() - 1)) : new Integer(nextFlow.get(0).getApprovalTerm());
            nextRecord.setApprovalCurrentLimitTime(term);
            nextRecord.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
        }
        nextRecord.setId(StringUtils.uuid());
        JSONObject baseInfoRequest = new JSONObject();
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(approvalAuditDto.getCaseId());
        String documentCatalogCode = getMergeDocumentCatalogCode(caseMainDetailInfo.getInvestConclusion());
        if (StringUtils.isBlank(approvalAuditDto.getNextHandler())) {
            CaseMainInfo mainInfo = new CaseMainInfo();
            BeanUtils.copyProperties(caseMainInfo, mainInfo);
            NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(mainInfo, nextFlow.get(0).getApprovalRole(), documentCatalogCode);
            nextRecord.setApprovalUserId(vo.getUserId());
            approvalAuditDto.setNextHandler(vo.getUserId());
            approvalAuditDto.setAutoTime(vo.getAutoTime());
            approvalAuditDto.setIsAutoApproval(vo.getIsAutoApproval());
        } else {
            nextRecord.setApprovalUserId(approvalAuditDto.getNextHandler());
            if (Constant.STRING_1.equals(approvalAuditDto.getIsAutoApproval())) {
                CaseMainInfo mainInfo = new CaseMainInfo();
                BeanUtils.copyProperties(caseMainInfo, mainInfo);
                NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(mainInfo, nextFlow.get(0).getApprovalRole(), documentCatalogCode);
                approvalAuditDto.setNextHandler(vo.getUserId());
                approvalAuditDto.setAutoTime(vo.getAutoTime());
                approvalAuditDto.setIsAutoApproval(vo.getIsAutoApproval());
            }
        }
        List<String> userIds = new ArrayList<>();
        userIds.addAll(Arrays.asList(approvalAuditDto.getNextHandler().split(",")));
        baseInfoRequest.put("userIds", userIds);
        if (StringUtils.isNotBlank(approvalAuditDto.getApprovalCenterOrgCode())) {
            List<String> orgCodes = new ArrayList<>();
            orgCodes.add(approvalAuditDto.getApprovalCenterOrgCode());
            baseInfoRequest.put("orgCodes", orgCodes);
        }
        //baseInfoRequest.put("orgCodes",approvalAuditDto.getApprovalCenterOrgCode());
        List<ZfPeopleBaseInfoVO> baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userIds", userIds);
        if (null != userIds && userIds.size() > 0) {
            List<String> userNameList = memberUserSignMapper.selectUserNameList(paramMap);
            if (null != userNameList && userNameList.size() > 0) {
                StringJoiner stringJoiner = new StringJoiner(",");
                for (String userName : userNameList) {
                    stringJoiner.add(userName);
                }
                nextRecord.setApprovalUserName(stringJoiner.toString());
            } else {
                nextRecord.setApprovalUserName("");
            }
        } else {
            nextRecord.setApprovalUserName("");
        }
        nextRecord.setApprovalNum(nextFlow.get(0).getApprovalOrderNum());
        nextRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
        nextRecord.setFlowRelationId(nextFlow.get(0).getId());
        if (StringUtils.isNotBlank(approvalAuditDto.getApprovalCenterOrgName())) {
            nextRecord.setApprovalOrgName(approvalAuditDto.getApprovalCenterOrgName());
            if (approvalAuditDto.getApprovalCenterOrgName().contains("联合法制审核")) {
                String approvalCenterOrgName = approvalAuditDto.getApprovalCenterOrgName();
                approvalCenterOrgName = approvalCenterOrgName.substring(approvalCenterOrgName.indexOf("（") + 1, approvalCenterOrgName.indexOf("）"));
                nextRecord.setApprovalOrgName(approvalCenterOrgName);
                nextRecord.setApprovalOrgCode(approvalAuditDto.getApprovalCenterOrgCode());
            }
        } else {
            nextRecord.setApprovalOrgCode(caseMainInfo.getCaseOrgCode());
        }
        nextRecord.setPartyId(partyId);
        nextRecord.setAutoTime(approvalAuditDto.getAutoTime());
        nextRecord.setIsAutoApproval(approvalAuditDto.getIsAutoApproval());
        nextRecord.setAddTime(new Date());
        int nextIn = caseApprovalWaitRecordMapper.insert(nextRecord);
        return result;


    }

    /**
     * 审批通过（合并审批）
     *
     * @param approvalAuditDto
     * @return {@link Map< Object, Object>}
     * @author liyafeng
     * @date 2023/4/27
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public Map<String, Object> doAgreeAuditMerge(ApprovalAgreeAuditDto approvalAuditDto) {
        //默认不是最后最后审批节点
        boolean isLast = false;
        //读取当前用户，获取当前审批环节
        UserDTO userDTO = UserUtil.getUserInfo();
        String partyId = approvalAuditDto.getPartyId();
        String docId = approvalAuditDto.getDocId();
        List<CaseApprovalWaitRecord> currentRecord = null;
        List<CaseDocumentRecord> caseDocumentRecords = null;
        /*if(StringUtils.isNotBlank(docId)){
            Example waitExample = new Example(CaseApprovalWaitRecord.class);
            waitExample.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("docId",docId);
            currentRecord = caseApprovalWaitRecordMapper.selectByExample(waitExample);
            Example docRecordExample = new Example(CaseDocumentRecord.class);
            docRecordExample.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("id",docId).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId());
            caseDocumentRecords = caseDocumentRecordMapper.selectByExample(docRecordExample);
        }*/
        if (org.springframework.util.ObjectUtils.isEmpty(currentRecord)) {
            Example example = new Example(CaseApprovalWaitRecord.class);
            Example.Criteria criteria = example.createCriteria();
            if (StringUtils.isBlank(partyId)) {
                criteria.andEqualTo("caseId", approvalAuditDto.getCaseId());
            } else {
                criteria.andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("partyId", partyId);
            }
            if (StringUtils.isNotBlank(approvalAuditDto.getDocumentCatalogCode())) {
                criteria.andEqualTo("documentId", approvalAuditDto.getDocumentCatalogCode());
            }
            currentRecord = caseApprovalWaitRecordMapper.selectByExample(example);
        }
        //如果待审批记录不存在 则提示无审批记录
        if (currentRecord.isEmpty()) {
            throw new BusinessException("当前无审批任务");
        }
        //校验登录人的id是否为审批人
       /* String userId=userDTO.getUserId().toString();
        if(!currentRecord.get(0).getApprovalUserId().contains(userId)){
            throw new BusinessException("当前待审批记录，已被其他人审批，请刷新当前页面！");
        }*/
        //删除待审批节点
        int del = caseApprovalWaitRecordMapper.deleteByPrimaryKey(currentRecord.get(0).getId());
        //查询案件信息
        String caseId = approvalAuditDto.getCaseId();
        CaseMainInfoVo caseMainInfo = caseMainInfoMapper.selectCaseMainInfo(caseId);
        Map<String, Object> result = new HashMap<>(8);
        //已审批通过记录保存
        int completeIn = getCompleteIn(approvalAuditDto, currentRecord);
        //获取审批relation
        CaseApprovalFlowRelation caseApprovalFlowRelation = caseDocuApprovalFolwRelationMapper.selectByPrimaryKey(currentRecord.get(0).getFlowRelationId());
        if (caseApprovalFlowRelation == null) {
            throw new BusinessException("未匹配到审批流关联配置信息-flowRelationId:" + currentRecord.get(0).getFlowRelationId());
        }
        Example example1 = new Example(CaseApprovalFlowRelation.class);
        example1.createCriteria().andEqualTo("documentCatalogCode", caseApprovalFlowRelation.getDocumentCatalogCode()).andEqualTo("approvalFlowVerson", caseApprovalFlowRelation.getApprovalFlowVerson()).andEqualTo("approvalFlowId", caseApprovalFlowRelation.getApprovalFlowId());
        List<CaseApprovalFlowRelation> caseApprovalFlowRelations = caseDocuApprovalFolwRelationMapper.selectByExample(example1);
        //合并审批需要拆分文书目录编码
        String[] documentCatalogCodeArr = approvalAuditDto.getDocumentCatalogCode().split(Constant.STRING_COMMA);
        if (ObjectUtils.isEmpty(documentCatalogCodeArr)) {
            throw new BusinessException("文书目录编码传参异常");
        }
        List<String> documentCatalogCodeList = Arrays.asList(documentCatalogCodeArr);
        for (String documentCatalogCode : documentCatalogCodeList) {
            //获取文书记录
            docId = currentRecord.get(0).getDocId();
            Example exampleDocRecord = new Example(CaseDocumentRecord.class);
            if (StringUtils.isNotBlank(docId)) {
                exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("id", docId);
            } else {
                if (StringUtils.isBlank(partyId)) {
                    exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", documentCatalogCode).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                } else {
                    exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("partyId", partyId).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                }
            }
            caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDocRecord);
            //是最后一个节点
            Map<String, Object> result1 = finalNodeProcessMergeAuto(approvalAuditDto, currentRecord, del, completeIn, caseApprovalFlowRelations, result, caseDocumentRecords, partyId, approvalAuditDto.getCaseAssistId(), documentCatalogCode);
            String closeSignal = MapUtils.getString(result1, "closeSignal", "");
            if ("CLOSE-TRIGGER-APPROVAL-PASS".equals(closeSignal)) {
                // 发送审批完成,提交人钉钉提醒
                //sendDingAuditFinish(currentRecord,"YES");
                //sendDingAuditFinishMsg(currentRecord,"YES");
                return result1;
            }
            if (result1 != null) {
                // 发送审批完成,提交人钉钉提醒
                //sendDingAuditFinish(currentRecord,"YES");
                //sendDingAuditFinishMsg(currentRecord,"YES");
                continue;
            }
            // 生成审批后文书
            String approvalStatus = DocumentStatusEnum.CHECKING.getCode();
            makeDoc(currentRecord.get(0).getFlowRelationId(), approvalAuditDto.getCaseId(), documentCatalogCode, caseDocumentRecords.get(0), approvalAuditDto.getOpinion(), isLast, approvalStatus, partyId, approvalAuditDto.getCaseAssistId(), currentRecord.get(0).getIsEditApproval(), currentRecord.get(0).getDocId(), null);
        }
        //查询配置表
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(currentRecord.get(0), "");
        int sortNum = Integer.valueOf(currentRecord.get(0).getApprovalNum());
        //不是最后一个节点，下一审批人必传
        if (StringUtils.isBlank(approvalAuditDto.getNextHandler()) && caseApprovalFlowRelations.size() > sortNum) {
            throw new BusinessException("系统异常，下一环节处理人必选！");
        }
        //判断审批记录是否存在
        boolean isExist = checkCaseApprovalWaitRecordIsExist(caseId, currentRecord.get(0).getDocumentId(), partyId);
        //boolean isExist=checkCaseApprovalWaitRecordIsExist(approvalAuditDto.getCaseId(),currentRecord.get(0).getDocumentId(),partyId);
        if (isExist) {
            throw new BusinessException("审批通过失败，生成待审批记录已存在，请勿重复提交!");
        }
        CaseApprovalWaitRecord nextRecord = new CaseApprovalWaitRecord();
        BeanUtils.copyProperties(currentRecord.get(0), nextRecord);
        if (StringUtils.isNotBlank(nextFlow.get(0).getApprovalTerm())) {
            Integer term = nextFlow.get(0).getApprovalTerm().contains("天") ? new Integer(nextFlow.get(0).getApprovalTerm().substring(0, nextFlow.get(0).getApprovalTerm().length() - 1)) : new Integer(nextFlow.get(0).getApprovalTerm());
            nextRecord.setApprovalCurrentLimitTime(term);
            nextRecord.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
        }
        nextRecord.setId(StringUtils.uuid());
        JSONObject baseInfoRequest = new JSONObject();
        if (StringUtils.isBlank(approvalAuditDto.getNextHandler())) {
            CaseMainInfo mainInfo = new CaseMainInfo();
            BeanUtils.copyProperties(caseMainInfo, mainInfo);
            NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(mainInfo, nextFlow.get(0).getApprovalRole(), approvalAuditDto.getDocumentCatalogCode());
            nextRecord.setApprovalUserId(vo.getUserId());
            approvalAuditDto.setNextHandler(vo.getUserId());
            approvalAuditDto.setAutoTime(vo.getAutoTime());
            approvalAuditDto.setIsAutoApproval(vo.getIsAutoApproval());
        } else {
            nextRecord.setApprovalUserId(approvalAuditDto.getNextHandler());
            if (Constant.STRING_1.equals(approvalAuditDto.getIsAutoApproval())) {
                CaseMainInfo mainInfo = new CaseMainInfo();
                BeanUtils.copyProperties(caseMainInfo, mainInfo);
                NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(mainInfo, nextFlow.get(0).getApprovalRole(), approvalAuditDto.getDocumentCatalogCode());
                approvalAuditDto.setNextHandler(vo.getUserId());
                approvalAuditDto.setAutoTime(vo.getAutoTime());
                approvalAuditDto.setIsAutoApproval(vo.getIsAutoApproval());
            }
        }
        List<String> userIds = new ArrayList<>();
        userIds.addAll(Arrays.asList(approvalAuditDto.getNextHandler().split(",")));
        baseInfoRequest.put("userIds", userIds);
        if (StringUtils.isNotBlank(approvalAuditDto.getApprovalCenterOrgCode())) {
            List<String> orgCodes = new ArrayList<>();
            orgCodes.add(approvalAuditDto.getApprovalCenterOrgCode());
            baseInfoRequest.put("orgCodes", orgCodes);
        }
        //baseInfoRequest.put("orgCodes",approvalAuditDto.getApprovalCenterOrgCode());
        List<ZfPeopleBaseInfoVO> baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userIds", userIds);
        if (null != userIds && userIds.size() > 0) {
            List<String> userNameList = memberUserSignMapper.selectUserNameList(paramMap);
            if (null != userNameList && userNameList.size() > 0) {
                StringJoiner stringJoiner = new StringJoiner(",");
                for (String userName : userNameList) {
                    stringJoiner.add(userName);
                }
                nextRecord.setApprovalUserName(stringJoiner.toString());
            } else {
                nextRecord.setApprovalUserName("");
            }
        } else {
            nextRecord.setApprovalUserName("");
        }
        nextRecord.setApprovalNum(nextFlow.get(0).getApprovalOrderNum());
        nextRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
        nextRecord.setFlowRelationId(nextFlow.get(0).getId());
        if (StringUtils.isNotBlank(approvalAuditDto.getApprovalCenterOrgName())) {
            nextRecord.setApprovalOrgName(approvalAuditDto.getApprovalCenterOrgName());
            if (approvalAuditDto.getApprovalCenterOrgName().contains("联合法制审核")) {
                String approvalCenterOrgName = approvalAuditDto.getApprovalCenterOrgName();
                approvalCenterOrgName = approvalCenterOrgName.substring(approvalCenterOrgName.indexOf("（") + 1, approvalCenterOrgName.indexOf("）"));
                nextRecord.setApprovalOrgName(approvalCenterOrgName);
                nextRecord.setApprovalOrgCode(approvalAuditDto.getApprovalCenterOrgCode());
            }
        } else {
            nextRecord.setApprovalOrgCode(caseMainInfo.getCaseOrgCode());
        }
        nextRecord.setPartyId(partyId);
        nextRecord.setAutoTime(approvalAuditDto.getAutoTime());
        nextRecord.setIsAutoApproval(approvalAuditDto.getIsAutoApproval());
        int nextIn = caseApprovalWaitRecordMapper.insert(nextRecord);
        result.put("caseId", approvalAuditDto.getCaseId());
        //速结程序判断下个节点是否自动审批
        if (Constant.STRING_3.equals(caseMainInfo.getCaseType())) {
            String closeSignal = "";
            ApprovalGeneralSubmitDto dto = new ApprovalGeneralSubmitDto();
            BeanUtils.copyProperties(approvalAuditDto, dto);
            String documentCatalogCode = approvalAuditDto.getDocumentCatalogCode();
            if (Constant.STRING_1.equals(dto.getIsMerge())) {
                CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(dto.getCaseId());
                documentCatalogCode = getMergeDocumentCatalogCode(caseMainDetailInfo.getInvestConclusion());
                // dto.setDocumentCatalogCode(documentCatalogCode);
            }
            //dto.setDocumentCatalogCode(currentRecord.get(0).getDocumentId());
            ApprovalAgreeAuditDto approvalAgreeAuditDto = getApprovalAgreeAuditMergeDto(dto);
            approvalAgreeAuditDto.setNowHandler(dto.getNextHandler());
            //CaseMainDetailInfo caseMainDetailInfo=caseMainDetailInfoMapper.selectByPrimaryKey(dto.getCaseId());
            //String documentCatalogCode=getMergeDocumentCatalogCode(caseMainDetailInfo.getInvestConclusion());
            approvalAgreeAuditDto.setDocumentCatalogCode(approvalAuditDto.getDocumentCatalogCode());
            if (Constant.STRING_1.equals(approvalAgreeAuditDto.getIsAutoApproval())) {
                for (int i = 0; i < 4; i++) {
                    //如果下个环节是自动审批
                    if (Constant.STRING_1.equals(approvalAgreeAuditDto.getIsAutoApproval())) {
                        Long autoTime = Long.valueOf(approvalAgreeAuditDto.getAutoTime());
                        try {
                            //Thread.sleep(autoTime * 1000);
                            Thread.sleep(autoTime);
                            Map<String, Object> agreeResult = doAgreeAuditMergeAuto(approvalAgreeAuditDto);
                            closeSignal = MapUtils.getString(agreeResult, "closeSignal", "");
                            //result.put("closeSignal", "CLOSE-TRIGGER-APPROVAL-PASS");
                            if ("CLOSE-TRIGGER-APPROVAL-PASS".equals(closeSignal)) {
                                cfRedisRepository.set("IS_APPROVAL_AUTO_PASS" + dto.getCaseId(), "true");
                                break;
                            }
                            String nowHandler = approvalAgreeAuditDto.getNextHandler();
                            approvalAgreeAuditDto = getApprovalAgreeAuditDto(dto);
                            approvalAgreeAuditDto.setNowHandler(nowHandler);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        cfRedisRepository.set("IS_APPROVAL_AUTO_PASS" + dto.getCaseId(), "true");
                        break;
                    }
                }

            }
        }
        return result;
    }

    /**
     * 合并审批审批退回
     *
     * @param approvalAuditDto
     * @return {@link Map< Object, Object>}
     * @author liyafeng
     * @date 2023/5/6
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    @WorkFlowRollAnnotation
    public Map<String, Object> doReturnAuditMerge(ApprovalReturnlAuditDto approvalAuditDto) {
        CaseMainInfoVo caseMainInfo = caseMainInfoMapper.selectCaseMainInfo(approvalAuditDto.getCaseId());
        String handleType = caseMainInfo.getHandleType();
        UserDTO userDTO = UserUtil.getUserInfo();
        //获取当前待审批记录
        List<CaseApprovalWaitRecord> currentRecords = getReturnCaseApprovalWaitRecord(approvalAuditDto);
        List<CaseDocumentRecord> caseDocumentRecords = null;
        //删除待审批节点
        //已审批通过记录保存
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        BeanUtils.copyProperties(currentRecords.get(0), caseApprovalCompleteRecord);
        caseApprovalCompleteRecord.setId(StringUtils.uuid());
        caseApprovalCompleteRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_RETURN);
        caseApprovalCompleteRecord.setApprovalTime(new Date());
        caseApprovalCompleteRecord.setApprovalUserId(userDTO.getUserId().toString());
        caseApprovalCompleteRecord.setApprovalOpinion(approvalAuditDto.getOpinion());
        caseApprovalCompleteRecord.setApprovalUserName(userDTO.getRealName());
        caseApprovalCompleteRecord.setApprovalBackType(approvalAuditDto.getReturnNode());
        caseApprovalCompleteRecord.setApprovalOrgName(userDTO.getOrgName());
        caseApprovalCompleteRecord.setApprovalOrgCode(userDTO.getOrgCode());
        int completeIn = caseApprovalCompleteRecordMapper.insert(caseApprovalCompleteRecord);
        int del = caseApprovalWaitRecordMapper.deleteByPrimaryKey(currentRecords.get(0).getId());
        // 退回节点 上一节点，发起人
        //退回到发起人操作
        String start = "start";
        String one = "1";
        Map<String, Object> result = new HashMap<>(8);
        //合并审批需要拆分文书目录编码
        String[] documentCatalogCodeArr = approvalAuditDto.getDocumentCatalogCode().split(Constant.STRING_COMMA);
        if (ObjectUtils.isEmpty(documentCatalogCodeArr)) {
            throw new BusinessException("文书目录编码传参异常");
        }
        List<String> documentCatalogCodeList = Arrays.asList(documentCatalogCodeArr);
        for (String documentCatalogCode : documentCatalogCodeList) {
            Example exampleDocRecord = new Example(CaseDocumentRecord.class);
            if (StringUtils.isBlank(approvalAuditDto.getPartyId())) {
                exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", documentCatalogCode).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode()).andNotEqualTo("documentApprovalStatus", DocumentStatusEnum.CHECK_END.getCode());
            } else {
                exampleDocRecord.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("partyId", approvalAuditDto.getPartyId()).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode()).andNotEqualTo("documentApprovalStatus", DocumentStatusEnum.CHECK_END.getCode());
            }
            caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDocRecord);
            //退回发起人需要清除审批意见
            if (start.equals(approvalAuditDto.getReturnNode()) || one.equals(currentRecords.get(0).getApprovalNum())) {
                //案源来源审批数据 提交审批完成后 新增流转日志
                //判断是否需要保存日志
                // 文书状态改为未提交:修改文书表状态
                if (caseDocumentRecords.isEmpty()) {
                    throw new BusinessException("未匹配到文书记录-doReturnAudit");
                }
                CaseDocumentRecord caseDocumentRecordForUpdate = caseDocumentRecords.get(0);
                caseDocumentRecordForUpdate.setDocumentAuditStatus("return");
                caseDocumentRecordForUpdate.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_BACK.getCode());
                // 清空审批意见
                clearOpinion(caseDocumentRecordForUpdate);
                // 更新关联文书
                //updateRelationDocStatus(caseDocumentRecordForUpdate.getDocumentCatalogCode(),"return",approvalAuditDto.getCaseId(),approvalAuditDto.getPartyId());
                this.updateRelationDocStatusByApprovalDocumentId(caseDocumentRecordForUpdate.getDocumentCatalogCode(), "return", approvalAuditDto.getCaseId(), approvalAuditDto.getPartyId(), "");
                caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecordForUpdate);
                if (!Constant.STRING_1.equals(currentRecords.get(0).getIsEditApproval())) {
                    result.put("workId", approvalAuditDto.getCaseId());
                }
                List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentCatalogCode(caseMainInfo.getId(), caseMainInfo, caseDocumentRecordForUpdate.getDocumentCatalogCode());
                String documentLinkObjectType = configBusiParamDocumentInfo.get(0).getDocumentLinkObjectType();
                if (Constant.STRING_2.equals(handleType) && Constant.STRING_2.equals(documentLinkObjectType)) {
                    result.put("workSubId", approvalAuditDto.getPartyId());
                }
                if ("DC1A0223300CFGZSPB000000001".equals(documentCatalogCode) || "DC1A0223300BYCFGZSPB0000001".equals(documentCatalogCode)) {
                    result.put("stepSignal", "STEP-RETURN");
                    result.put("documentCatalogCode", caseDocumentRecordForUpdate.getDocumentCatalogCode());
                    return result;
                }
            }

        }
        // 退回上一步操作
        String prior = "prior";
        if (prior.equals(approvalAuditDto.getReturnNode())) {
            // 查询上一环节时效
            List<CaseApprovalFlowRelation> priorflows = getPriorCaseApprovalFlow(currentRecords);
            if (priorflows.isEmpty()) {
                throw new BusinessException("未匹配到上一环节审批流配置信息");
            }
            //找出上一步操作记录,插入待审批表
            // 返回上个节点查询上个节点信息
            Example exampleComplete = new Example(CaseApprovalCompleteRecord.class);
            if (StringUtils.isBlank(approvalAuditDto.getPartyId())) {
                exampleComplete.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andGreaterThan("approvalNum", "0").andEqualTo("documentId", currentRecords.get(0).getDocumentId()).andEqualTo("flowRelationId", priorflows.get(0).getId());
            } else {
                exampleComplete.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andGreaterThan("approvalNum", "0").andEqualTo("documentId", currentRecords.get(0).getDocumentId()).andEqualTo("flowRelationId", priorflows.get(0).getId()).andEqualTo("partyId", approvalAuditDto.getPartyId());
            }
            //排序查询时间倒序
            exampleComplete.orderBy("approvalTime").desc();
            List<CaseApprovalCompleteRecord> caseApprovalCompleteRecords = caseApprovalCompleteRecordMapper.selectByExample(exampleComplete);
            if (caseApprovalCompleteRecords.isEmpty()) {
                throw new BusinessException("审批完成记录为空");
            }
            //判断审批记录是否存在
            boolean isExist = checkCaseApprovalWaitRecordIsExist(approvalAuditDto.getCaseId(), currentRecords.get(0).getDocumentId(), approvalAuditDto.getPartyId());
            if (isExist) {
                throw new BusinessException("审批退回失败，待审批记录已存在!");
            }
            CaseApprovalWaitRecord newWaitNode = new CaseApprovalWaitRecord();
            BeanUtils.copyProperties(caseApprovalCompleteRecords.get(0), newWaitNode);
            newWaitNode.setId(StringUtils.uuid());
            newWaitNode.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
            if (StringUtils.isNotBlank(priorflows.get(0).getApprovalTerm())) {
                Integer term = priorflows.get(0).getApprovalTerm().contains("天") ? new Integer(priorflows.get(0).getApprovalTerm().substring(0, priorflows.get(0).getApprovalTerm().length() - 1)) : new Integer(priorflows.get(0).getApprovalTerm());
                newWaitNode.setApprovalCurrentLimitTime(term);
                newWaitNode.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
                newWaitNode.setFlowRelationId(priorflows.get(0).getId());
            }
            int newIn = caseApprovalWaitRecordMapper.insert(newWaitNode);
            Boolean f = (newIn == 1 && del == 1 && completeIn == 1);
            if (f) {
                result.put("documentCatalogCode", "");//看不懂用来干啥的，先这样吧，头疼
            } else {
                throw new BusinessException("审批退回数据处理时出现异常");
            }
        }
        return result;
    }


    @Override
    public NextAuditUserVo getNextAutoAuditUserVo(String caseId, String documentCatalogCode) {
        //结案报告提交审批
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(null, documentCatalogCode);
        if (ObjectUtil.isEmpty(nextFlow)) {
            throw new BusinessException("未查询到审批信息");
        }
        CaseApprovalFlowRelation flowRelation = nextFlow.get(0);
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (ObjectUtil.isNotEmpty(caseMainInfo)) {
            String roleId = flowRelation.getApprovalRole();
            String caseType = caseMainInfo.getCaseType();
            if (CaseTypeEnum.SIMPLE_QUICK.getCode().equals(caseType) || CaseTypeEnum.FAST_PROCEDURE.getCode().equals(caseType)) {
                NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(caseMainInfo, roleId, documentCatalogCode);
                if (vo != null) {
                    return vo;
                }
            }
        }
        return null;
    }

    /**
     * 获取退回待审批记录（合并审批）
     *
     * @param approvalAuditDto
     * @return {@link List< CaseApprovalWaitRecord>}
     * @author liyafeng
     * @date 2023/5/6
     */
    private List<CaseApprovalWaitRecord> getReturnCaseApprovalWaitRecord(ApprovalReturnlAuditDto approvalAuditDto) {
        List<CaseApprovalWaitRecord> currentRecord = new ArrayList<>();
        String docId = approvalAuditDto.getDocId();
        if (StringUtils.isNotBlank(docId)) {
            Example waitExample = new Example(CaseApprovalWaitRecord.class);
            waitExample.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("docId", docId);
            currentRecord = caseApprovalWaitRecordMapper.selectByExample(waitExample);
           /* Example docRecordExample = new Example(CaseDocumentRecord.class);
            docRecordExample.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("id",docId).andEqualTo("documentCatalogCode", currentRecord.get(0).getDocumentId()).andNotEqualTo("documentApprovalStatus",DocumentStatusEnum.CHECK_END.getCode());
            caseDocumentRecords = caseDocumentRecordMapper.selectByExample(docRecordExample);*/
        }
        if (org.springframework.util.ObjectUtils.isEmpty(currentRecord)) {
            //删除当前节点
            Example example = new Example(CaseApprovalWaitRecord.class);
            if (StringUtils.isBlank(approvalAuditDto.getPartyId())) {
                example.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("documentId", approvalAuditDto.getDocumentCatalogCode());
            } else {
                example.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("partyId", approvalAuditDto.getPartyId()).andEqualTo("documentId", approvalAuditDto.getDocumentCatalogCode());
            }
            currentRecord = caseApprovalWaitRecordMapper.selectByExample(example);
        }
        if (currentRecord.isEmpty()) {
            throw new BusinessException("当前无审批任务");
        }
        return currentRecord;
    }

    /**
     * 合并审批完成处理
     *
     * @param approvalAuditDto
     * @param currentRecord
     * @param del
     * @param completeIn
     * @param caseApprovalFlowRelations
     * @param result
     * @param caseDocumentRecords
     * @param partyId
     * @param caseAssistId
     * @param documentCatalogCode
     * @return {@link Map< String, Object>}
     * @author liyafeng
     * @date 2023/4/27
     */
    private Map<String, Object> finalNodeProcessMergeAuto(ApprovalAgreeAuditDto approvalAuditDto, List<CaseApprovalWaitRecord> currentRecord, int del, int completeIn, List<CaseApprovalFlowRelation> caseApprovalFlowRelations, Map<String, Object> result, List<CaseDocumentRecord> caseDocumentRecords, String partyId, String caseAssistId, String documentCatalogCode) {
        if (Integer.valueOf(currentRecord.get(0).getApprovalNum()) == caseApprovalFlowRelations.size()) {
            // 只需要存入审批完成，删除待审批记录
            if (del == 1 && completeIn == 1) {
                //文书状态更改
                if (caseDocumentRecords.isEmpty()) {
                    throw new BusinessException("最后审批节点处理传入文书记录为空");
                }
                caseDocumentRecords = caseDocumentRecords.stream().filter(e -> DocumentStatusEnum.CHECKING.getCode().equals(e.getDocumentApprovalStatus())).collect(Collectors.toList());
                CaseDocumentRecord caseDocumentRecordForUpdate = caseDocumentRecords.get(0);
                caseDocumentRecordForUpdate.setDocumentAuditStatus("pass");
                caseDocumentRecordForUpdate.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_END.getCode());
                caseDocumentRecordForUpdate.setDocumentApprovalTime(LocalDateTime.now());
                //判断是否需要更新案件状态，查询配置表
                if (caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecordForUpdate) == 1) {
                    // 更新关联文书
                    updateRelationDocStatus(caseDocumentRecordForUpdate.getDocumentCatalogCode(), "pass", approvalAuditDto.getCaseId(), partyId);
                    result.put("caseId", approvalAuditDto.getCaseId());
                    // 生成审批完成文书
                    invokeDocMergeAuto(approvalAuditDto, currentRecord, caseDocumentRecords, partyId, caseAssistId, documentCatalogCode);
                    updateMainMergeAuto(approvalAuditDto, currentRecord, documentCatalogCode);
                    //保存案源审批通过流转日志
                    CaseMainInfoVo caseMainInfo = caseMainInfoMapper.selectCaseMainInfo(approvalAuditDto.getCaseId());
                    boolean isSaveCaseSourceFolw = getIsSaveCaseSourceFolwLog(caseMainInfo, currentRecord.get(0).getDocumentId());
                    if (isSaveCaseSourceFolw) {
                        saveCaseSourceApprovalFlow(caseMainInfo);
                    }
                    if ("DC1A0223300CFGZSPB000000001".equals(documentCatalogCode) || "DC1A0223300BYCFGZSPB0000001".equals(documentCatalogCode)) {
                        result.put("closeSignal", "CLOSE-TRIGGER-APPROVAL-PASS");
                    }
                    return result;
                } else {
                    throw new BusinessException("更新文书记录信息时出现异常");
                }
            } else {
                throw new BusinessException("最后审批节点数据处理时出现异常");
            }
        }
        return null;
    }

    private void updateMainMergeAuto(ApprovalAgreeAuditDto approvalAuditDto, List<CaseApprovalWaitRecord> currentRecord, String documentCatalogCode) {
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(approvalAuditDto.getCaseId());
        String laspb = "LASPB";
        if (laspb.equals(documentKindCode)) {
            CaseMainInfo updateCaseMainInfo = new CaseMainInfo();
            updateCaseMainInfo.setId(approvalAuditDto.getCaseId());
            updateCaseMainInfo.setCaseRegistTime(LocalDateTime.now());
            //应急办案期限是30天，其他是90天
            if (TerritoryCodeEnum.YJGL.getCode().equals(caseMainInfo.getCaseTerritoryCode())) {
                updateCaseMainInfo.setCaseTimelimit(LocalDateTime.now().plusDays(30));
                updateCaseMainInfo.setCaseDeadline(30);
            } else {
                // 截止时间目前写死，后面读取配置
                updateCaseMainInfo.setCaseTimelimit(LocalDateTime.now().plusDays(90));
                updateCaseMainInfo.setCaseDeadline(90);
            }
            caseMainInfoMapper.updateByPrimaryKeySelective(updateCaseMainInfo);
            CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
            updateCaseMainDetailInfo.setCaseId(approvalAuditDto.getCaseId());
            updateCaseMainDetailInfo.setCaseRegisterTime(DateUtils.formatDate(new Date(), "yyyy年MM月dd日"));
            caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);

            //检查转处罚案件,调用处罚结果回传
            caseRegisterService.sendDisposalBackResult(approvalAuditDto.getCaseId());
        } else if (DocumentKindEnum.DOC_KIND_DK1SXFZAJYSSPB.getCode().equals(documentKindCode)) {
            //涉嫌犯罪案件移送书审批通过后
            //1.系统自动推送涉刑移送案件信息至两法衔接平台
            //2.案件状态变更为“已中止”
            CaseBaseInfoResponse caseBaseInfoResponse = caseTransferApiService.getTransferDetailAfterApproval(approvalAuditDto.getCaseId());
            Result result = lawenforceBusinessService.sendTransferDataByCaseBaseInfo(caseBaseInfoResponse);
            if (HttpStatus.HTTP_OK == result.getCode()) {
                //移送成功
                EditCaseStatusDto editCaseStatusDto = new EditCaseStatusDto();
                editCaseStatusDto.setCaseId(approvalAuditDto.getCaseId());
                //更新案件状态为中止
                editCaseStatusDto.setCaseChangeStatus(Constant.STRING_1);
                lawJoinService.editCaseStatusByLawJoinCallBack(editCaseStatusDto);
            }

        } else if (DocumentKindEnum.DOC_KIND_DK1BYLASPB.getCode().equals(documentKindCode) &&
                StrUtil.isNotEmpty(caseMainInfo.getLineCode()) && caseMainInfo.getLineCode().contains(TerritoryCodeEnum.RLSB.getCode())) {
            CollectReportDataDto dto = new CollectReportDataDto();
            dto.setCaseId(caseMainInfo.getId());
            dto.setCaseTerritoryCode(TerritoryCodeEnum.RLSB.getCode());
            dto.setCasePartyType("1");
            dataReportService.caseDataReport(dto);
        }
        //如果是撤销立案审批表，生成一条记录，然后定时重新上报已经上报成功的数据
        if (DocumentKindEnum.DOC_KIND_CXLASQB.getCode().equals(documentKindCode)) {
            String userId = "";
            UserDTO userInfo = UserUtil.getUserInfo();
            if (userInfo != null) {
                userId = String.valueOf(userInfo.getUserId());
            }
            caseDataChangeReportRecordService.save(approvalAuditDto.getCaseId(), CaseChangeOperationTypeEnum.OPERATION_TYPE_6.getCode(), userId);
        }
        CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
        updateCaseMainDetailInfo.setCaseId(approvalAuditDto.getCaseId());
        updateCaseMainDetailInfo.setSimpleFormType("-1");
        caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);
    }

    private void invokeDocMergeAuto(ApprovalAgreeAuditDto approvalAuditDto, List<CaseApprovalWaitRecord> currentRecord, List<CaseDocumentRecord> caseDocumentRecords, String partyId, String caseAssistId, String documentCatalogCode) {
        boolean isLast;
        isLast = true;
        String approvalStatus = DocumentStatusEnum.CHECK_END.getCode();
        Map<String, Object> resultMap = makeDocAuto(currentRecord.get(0).getFlowRelationId(), approvalAuditDto.getCaseId(), documentCatalogCode, caseDocumentRecords.get(0), approvalAuditDto.getOpinion(), isLast, approvalStatus, partyId, caseAssistId, approvalAuditDto.getNowHandler());
        String status = MapUtils.getString(resultMap, "success", "");
        String tr = "true";
        if (!tr.equals(status)) {
            throw new BusinessException("文书生成失败！");
        }
    }

    /**
     * 获取下个环节审批人
     *
     * @param dto
     * @return {@link List< NextAuditUserVo>}
     * @author liyafeng
     * @date 2023/4/25
     */
    private List<NextAuditUserVo> getNextNodeUserMerge(AuditNextUserQueryDto dto) {
        List<CaseApprovalWaitRecord> currentRecord = null;
        if (StringUtils.isNotBlank(dto.getDocId())) {
            Example example = new Example(CaseApprovalWaitRecord.class);
            example.createCriteria().andEqualTo("caseId", dto.getCaseId()).andEqualTo("docId", dto.getDocId());
            currentRecord = caseApprovalWaitRecordMapper.selectByExample(example);
        }
        if (ObjectUtils.isEmpty(currentRecord)) {
            Example example = new Example(CaseApprovalWaitRecord.class);
            if (StringUtils.isBlank(dto.getPartyId())) {
                example.createCriteria().andEqualTo("caseId", dto.getCaseId()).andEqualTo("documentId", dto.getDocumentCatalogCode());
            } else {
                example.createCriteria().andEqualTo("caseId", dto.getCaseId()).andEqualTo("documentId", dto.getDocumentCatalogCode()).andEqualTo("partyId", dto.getPartyId());
            }
            currentRecord = caseApprovalWaitRecordMapper.selectByExample(example);
        }

        List<NextAuditUserVo> nextAuditUsers = new ArrayList<>();
        CaseApprovalWaitRecord caseApprovalWaitRecord = null;
        if (null != currentRecord && currentRecord.size() > 0) {
            caseApprovalWaitRecord = currentRecord.get(0);
        }
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(dto.getCaseId());
        String documentCatalogCode = getMergeDocumentCatalogCode(caseMainDetailInfo.getInvestConclusion());
        //查询下一环节关联
        List<CaseApprovalFlowRelation> nextFlow = getNextCaseApprovalFlow(caseApprovalWaitRecord, documentCatalogCode);
        //判断是否当前文书最后一个审批节点校验
        if (nextFlow.isEmpty()) {
            NextAuditUserVo vo = new NextAuditUserVo();
            vo.setIsFinal("YES");
            nextAuditUsers.add(vo);
            return nextAuditUsers;
        }
        // 两种 方式调用member服务
        // 调用 member服务接口 根据角色 领域 执法区域 查询 用户信息
        // 调用List<User> users = userFeignApi.selectUserListByOgrCodeAndRoleName(userDTO.getOrgCode(),nextFlow.get(0).getApprovalRole());调用//
        //第二种 "/api/v2/member/zfPeople/yy/getZfPeopleBaseInfoList" 直接取
        CaseApprovalFlowRelation flowRelation = nextFlow.get(0);
        //判断是否配置自动审批
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(dto.getCaseId());
        //裁执分离可能没有案件信息
        if (ObjectUtil.isNotEmpty(caseMainInfo)) {
            String roleId = flowRelation.getApprovalRole();
            String caseType = caseMainInfo.getCaseType();
            if (Constant.STRING_3.equals(caseType)) {
                //速结程序
                NextAuditUserVo vo = configDefaultApprovalPersonService.getNextAuditUserVo(caseMainInfo, roleId, documentCatalogCode);
                if (null != vo) {
                    nextAuditUsers.add(vo);
                    return nextAuditUsers;
                }
            }
        }

        boolean isApprovalCenter = false;
        String one = "1";
        if (one.equals(flowRelation.getIsApprovalCenter())) {
            isApprovalCenter = true;
        }
        //获取上次选择的审批人的code
        String checkCode = getLastCheckCode(isApprovalCenter, flowRelation, dto);
        if (!isApprovalCenter) {
            if ("2".equals(dto.getType())) {//裁执分离
                getExecuteNextUsers(nextAuditUsers, nextFlow, dto.getCaseId(), checkCode);
            } else {//案件类型
                getNextUsers(nextAuditUsers, nextFlow, dto.getCaseId(), checkCode);
            }
        } else {
            if ("2".equals(dto.getType())) {//裁执分离

            } else {//案件类型
                getApprovalCenterNextUsers(nextAuditUsers, flowRelation, dto.getCaseId(), checkCode);
            }
        }
        //未提交查询第一个环节
        return nextAuditUsers;

    }

    /**
     * 生成完成审批记录
     *
     * @param caseApprovalWaitRecord
     * @return {@link CaseApprovalCompleteRecord}
     * @author liyafeng
     * @date 2023/4/24
     */
    private CaseApprovalCompleteRecord SaveCaseApprovalCompleteRecordMerge(CaseApprovalWaitRecord caseApprovalWaitRecord, ApprovalGeneralSubmitDto dto) {
        UserDTO userDTO = UserUtil.getUserInfo();
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        BeanUtils.copyProperties(caseApprovalWaitRecord, caseApprovalCompleteRecord);
        caseApprovalCompleteRecord.setId(StringUtils.uuid());
        caseApprovalCompleteRecord.setApprovalUserId("");
        caseApprovalCompleteRecord.setApprovalNum("0");
        caseApprovalCompleteRecord.setApprovalTime(new Date());
        JSONObject opinionJsonObject = new JSONObject();
        opinionJsonObject.put("informOpinion", dto.getInformOpinion());
        opinionJsonObject.put("opinion", dto.getOpinion());
        caseApprovalCompleteRecord.setApprovalOpinion(opinionJsonObject.toJSONString());
        caseApprovalCompleteRecord.setApprovalUserName(null);
        caseApprovalCompleteRecord.setApprovalOrgName(userDTO.getOrgName());
        caseApprovalCompleteRecord.setPartyId(dto.getPartyId());
        caseApprovalCompleteRecordMapper.insert(caseApprovalCompleteRecord);
        return caseApprovalCompleteRecord;
    }

    /**
     * 生成待审批记录
     *
     * @param documentCatalogCode
     * @param dto
     * @return
     * @author liyafeng
     * @date 2023/4/24
     */
    private CaseApprovalWaitRecord saveCaseApprovalWaitRecordMerge(CaseMainInfoVo caseMainInfo, String documentCatalogCode, ApprovalGeneralSubmitDto dto, List<CaseApprovalFlowRelation> nextFlows) {
        //判断审批记录是否存在
        String caseId = dto.getCaseId();
        boolean isExist = checkCaseApprovalWaitRecordIsExist(dto.getCaseId(), dto.getDocumentCatalogCode(), dto.getPartyId());
        if (isExist) {
            throw new BusinessException("生成待审批记录已存在，请勿重复提交!");
        }
        CaseApprovalWaitRecord caseApprovalWaitRecord = new CaseApprovalWaitRecord();
        caseApprovalWaitRecord.setId(StringUtils.uuid());
        caseApprovalWaitRecord.setApprovalNum(nextFlows.get(0).getApprovalOrderNum());
        caseApprovalWaitRecord.setCaseId(caseId);
        caseApprovalWaitRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
        if (StringUtils.isNotBlank(nextFlows.get(0).getApprovalTerm())) {
            Integer term = nextFlows.get(0).getApprovalTerm().contains("天") ? new Integer(nextFlows.get(0).getApprovalTerm().substring(0, nextFlows.get(0).getApprovalTerm().length() - 1)) : new Integer(nextFlows.get(0).getApprovalTerm());
            caseApprovalWaitRecord.setApprovalCurrentLimitTime(term);
            caseApprovalWaitRecord.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
        }
        UserDTO userDTO = UserUtil.getUserInfo();
        caseApprovalWaitRecord.setAddUserId(userDTO.getUserId().toString());
        caseApprovalWaitRecord.setAddUserName(userDTO.getRealName());
        caseApprovalWaitRecord.setDocumentId(dto.getDocumentCatalogCode());//待批传多个编码
        caseApprovalWaitRecord.setFlowRelationId(nextFlows.get(0).getId());
        //标题：行政处罚的相关审批任务标题为：当事人名称+“的”+文书名称；如“张三的立案审批表”
        //CaseMainInfoVo caseMainInfoVo=caseMainInfoMapper.selectCaseMainInfo(caseId);
        String title = "";
        Example examplePd = new Example(ConfigBusiParamDocumentInfo.class);
        examplePd.createCriteria().andEqualTo("documentCatalogCode", documentCatalogCode);
        List<ConfigBusiParamDocumentInfo> configBusiParamDocumentInfos = configBusiParamDocumentInfoMapper.selectByExample(examplePd);
        if (CaseStatusEnum.PUNISH_NO_REGISTER.getCode().equals(caseMainInfo.getCaseStatus()) && ApiVisitDataSourceEnum.PUNISH_AY.getCode().equals(caseMainInfo.getDataSource())) {
            Example example = new Example(CaseSourcePartyInfo.class);
            example.createCriteria().andEqualTo("caseSourceId", caseMainInfo.getId()).andEqualTo("status", Constant.STRING_1);
            List<CaseSourcePartyInfo> caseSourcePartyInfos = caseSourcePartyInfoMapper.selectByExample(example);
            if (caseSourcePartyInfos != null && caseSourcePartyInfos.size() > 0) {
                CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseMainInfo.getId());
                title = caseSourceRegisterMainInfo.getPartyName() + "的" + configBusiParamDocumentInfos.get(0).getDocumentKindName();
            } else {
                title = configBusiParamDocumentInfos.get(0).getDocumentKindName();
            }

        } else {
            List<CasePartiesRecordVo> partiesRecords = casePartiesRecordService.getCasePartiesInfo(caseId);
            CasePartiesRecordVo firstPartyInfo = partiesRecords.get(Constant.INTEGER_0);
            String showPartyName = firstPartyInfo.getPartyName();
            if (partiesRecords.size() == 1) {
                title = showPartyName + "的" + configBusiParamDocumentInfos.get(0).getDocumentKindName();
            } else if (partiesRecords.size() > 1) {
                title = showPartyName + "等" + partiesRecords.size() + "个的" + configBusiParamDocumentInfos.get(0).getDocumentKindName();
            }
        }
        caseApprovalWaitRecord.setApprovalTitle(title);
        caseApprovalWaitRecord.setAddTime(new Date());
        List<ZfPeopleBaseInfoVO> baseInfo = null;
        if (StringUtils.isBlank(dto.getNextHandler())) {
            AuditNextUserQueryDto queryDto = new AuditNextUserQueryDto();
            queryDto.setCaseId(caseId);
            queryDto.setDocumentCatalogCode(documentCatalogCode);
            List<NextAuditUserVo> users = getNextNodeUser(queryDto);
            caseApprovalWaitRecord.setApprovalUserId(users.get(0).getUserId());
            caseApprovalWaitRecord.setApprovalUserName(users.get(0).getRealName());
            caseApprovalWaitRecord.setApprovalOrgCode(caseMainInfo.getCaseOrgCode());
        } else {
            JSONObject baseInfoRequest = new JSONObject();
            List<String> userIds = Arrays.asList(dto.getNextHandler().split(","));
            baseInfoRequest.put("userIds", userIds);
            baseInfo = xzzfInterfaceService.getZfPeopleList(baseInfoRequest);
            caseApprovalWaitRecord.setApprovalUserId(dto.getNextHandler());
            StringJoiner stringJoiner = new StringJoiner(",");
            for (ZfPeopleBaseInfoVO vo : baseInfo) {
                stringJoiner.add(vo.getName());
            }
            caseApprovalWaitRecord.setApprovalOrgName(caseMainInfo.getCaseOrgName());
            caseApprovalWaitRecord.setApprovalUserName(stringJoiner.toString());
            caseApprovalWaitRecord.setApprovalOrgCode(caseMainInfo.getCaseOrgCode());
            caseApprovalWaitRecord.setPartyId(dto.getPartyId());
        }
        caseApprovalWaitRecord.setIsAutoApproval(dto.getIsAutoApproval());
        caseApprovalWaitRecord.setAutoTime(dto.getAutoTime());
        caseApprovalWaitRecord.setIsMerge(dto.getIsMerge());
        // 生成待审批记录
        caseApprovalWaitRecordMapper.insert(caseApprovalWaitRecord);
        return caseApprovalWaitRecord;
    }

    /**
     * 更新文书审批状态
     *
     * @param documentCatalogCode
     * @param dto
     * @return
     * @author liyafeng
     * @date 2023/4/24
     */
    private CaseDocumentRecord modifyCaseDocumentRecordApprovalStatus(String documentCatalogCode, ApprovalGeneralSubmitDto dto) {
        String caseId = dto.getCaseId();
        //更新文书记录表
        Example exampleDocRecord = new Example(CaseDocumentRecord.class);
        if (StringUtils.isBlank(dto.getPartyId())) {
            exampleDocRecord.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        } else {
            exampleDocRecord.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("partyId", dto.getPartyId()).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        }
        exampleDocRecord.orderBy("documentCreateTime").desc();
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(exampleDocRecord);
        if (caseDocumentRecords.isEmpty()) {
            throw new BusinessException("未匹配到文书记录");
        }
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecords.get(0);
        caseDocumentRecord.setDocumentAuditStatus("pending");
        caseDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.CHECKING.getCode());
        caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);
        return caseDocumentRecord;
    }

    /**
     * 【V1.11.0】描述： 最后审批节点处理(文书修改审批)
     *
     * @param approvalAuditDto
     * @param currentRecord
     * @param del
     * @param completeIn
     * @param caseApprovalFlowRelations
     * @param result
     * @param caseDocumentRecord
     * @return
     */
    private Map<String, Object> finalNodeProcessOfModifyDocument(ApprovalAgreeAuditDto approvalAuditDto, List<CaseApprovalWaitRecord> currentRecord, int del, int completeIn, List<CaseApprovalFlowRelation> caseApprovalFlowRelations, Map<String, Object> result, CaseDocumentRecord caseDocumentRecord) {
        if (Integer.valueOf(currentRecord.get(0).getApprovalNum()) == caseApprovalFlowRelations.size()) {
            // 只需要存入审批完成，删除待审批记录
            if (del == 1 && completeIn == 1) {
                caseDocumentRecord.setDocumentAuditStatus("pass");
                caseDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_END.getCode());
                caseDocumentRecord.setDocumentApprovalTime(LocalDateTime.now());
                //判断是否需要更新案件状态，查询配置表
                if (caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord) == 1) {
                    result.put("caseId", approvalAuditDto.getCaseId());
                    // 生成审批完成文书
                    invokeDocOfModifyDocument(caseDocumentRecord.getId());
                    caseDocumentRecordService.modifyDocumentRecordAfterApproval(currentRecord.get(0).getDocId());
                    return result;
                } else {
                    throw new BusinessException("更新文书记录信息时出现异常");
                }
            } else {
                throw new BusinessException("最后审批节点数据处理时出现异常");
            }
        }
        return null;
    }

    /**
     * 【V1.11.0】描述： 生成审批完成文书(文书修改审批)
     *
     * @param documentId
     */
    private void invokeDocOfModifyDocument(String documentId) {
        //重新生成文书
        Map<String, Object> paramJson = new HashMap<>(8);

        RebuildDocumentDto dto = new RebuildDocumentDto(documentId, "");
        List<RebuildDocumentDto> list = new ArrayList<>();
        list.add(dto);
        paramJson.put("documentInfo", list);
        Result<Map<String, Object>> result = stageDocCommonOperateService.rebuildPdf(paramJson);
        log.info("edit document,rebuild result :{}", result);
        int num = 0;
        if (ObjectUtil.isNotEmpty(result) && HttpStatus.HTTP_OK == result.getCode()) {
            num = (int) result.getData().get("num");
        }
        if (num == 0) {
            throw new BusinessException("修改文书失败,重新生成文书有误");
        }
    }


    /**
     * 【V1.11.0】描述： 审批退回(文书修改审批)
     *
     * @param approvalAuditDto
     * @return
     */
    @Override
    public Map<String, Object> doReturnAuditOfModifyDocument(ApprovalReturnlAuditDto approvalAuditDto) {
        CaseMainInfoVo caseMainInfo = caseMainInfoMapper.selectCaseMainInfo(approvalAuditDto.getCaseId());
        //读取当前用户，当前审批环节，校验角色权限，根据审批结果，流转下个节点
        // 校验审批权限 （不做了，能查到，数据存入时已校验处理）
        // 审批结果写入 case_approval_complete_record 已完成审批表 ，
        // 审批通过 写入下个节点  写入 待审批 case_approval_wait_record
        UserDTO userDTO = UserUtil.getUserInfo();
        String docId = approvalAuditDto.getDocId();
        if (StringUtils.isBlank(docId)) {
            throw new BusinessException("文书id不能为空");
        }

        Example waitExample = new Example(CaseApprovalWaitRecord.class);
        waitExample.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andEqualTo("docId", docId);
        List<CaseApprovalWaitRecord> currentRecord = caseApprovalWaitRecordMapper.selectByExample(waitExample);
        if (currentRecord.isEmpty()) {
            throw new BusinessException("当前无审批任务");
        }
        // 退回节点 上一节点，发起人
        //退回到发起人操作
        String start = "start";
        String one = "1";
        Map<String, Object> result = new HashMap<>(8);

        //删除待审批节点
        //已审批通过记录保存
        CaseApprovalCompleteRecord caseApprovalCompleteRecord = new CaseApprovalCompleteRecord();
        BeanUtils.copyProperties(currentRecord.get(0), caseApprovalCompleteRecord);
        caseApprovalCompleteRecord.setId(StringUtils.uuid());
        caseApprovalCompleteRecord.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_RETURN);
        caseApprovalCompleteRecord.setApprovalTime(new Date());
        caseApprovalCompleteRecord.setApprovalUserId(userDTO.getUserId().toString());
        caseApprovalCompleteRecord.setApprovalOpinion(approvalAuditDto.getOpinion());
        caseApprovalCompleteRecord.setApprovalUserName(userDTO.getRealName());
        caseApprovalCompleteRecord.setApprovalBackType(approvalAuditDto.getReturnNode());
        caseApprovalCompleteRecord.setApprovalOrgName(userDTO.getOrgName());
        caseApprovalCompleteRecord.setApprovalOrgCode(userDTO.getOrgCode());
        caseApprovalCompleteRecord.setDocId(docId);
        int completeIn = caseApprovalCompleteRecordMapper.insert(caseApprovalCompleteRecord);
        int del = caseApprovalWaitRecordMapper.deleteByPrimaryKey(currentRecord.get(0).getId());
        // 判断退回上一步是否发起人或退回环节为发起人
        if (start.equals(approvalAuditDto.getReturnNode()) || one.equals(currentRecord.get(0).getApprovalNum())) {
            //文书记录查询
            // 文书状态改为未提交:修改文书表状态
            CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(docId);
            if (ObjectUtils.isEmpty(caseDocumentRecord)) {
                throw new BusinessException("未匹配到文书记录-doReturnAudit");
            }
            caseDocumentRecord.setDocumentAuditStatus("return");
            caseDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.CHECK_BACK.getCode());
            //删除文书修改记录
            //caseDocumentModifyRecordService.deleteCaseDocumentModifyRecordByDocumentId(docId);
            // 清空审批意见
            //clearOpinion(caseDocumentRecordForUpdate);
            // 更新关联文书
            //updateRelationDocStatus(caseDocumentRecordForUpdate.getDocumentCatalogCode(),"return",approvalAuditDto.getCaseId(),approvalAuditDto.getPartyId());
            Boolean f = del == 1 && completeIn == 1 && caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord) == 1;
            if (f) {
                result.put("success", "true");
                result.put("msg", "成功");
            } else {
                throw new BusinessException("审批退回数据处理时出现异常");
            }
            // 生成文书
            // 文书审批退回 提交人钉钉提醒
            sendDingAuditFinishMsg(currentRecord, "NO");

            //工作台-消息提醒
            List<String> userIds = new ArrayList<>();
            userIds.add(currentRecord.get(0).getAddUserId());
            ConfigBusiParamDocumentInfo catalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(caseDocumentRecord.getDocumentCatalogCode());
            sendAuditFinishRetiredPcMsg(approvalAuditDto.getCaseId(), caseDocumentRecord.getDocumentCatalogCode(), catalogCode.getDocumentCatalogName(), currentRecord.get(0), caseMainInfo.getCaseOrgCode(), userIds);
            return result;
        }
        // 退回上一步操作
        String prior = "prior";
        if (prior.equals(approvalAuditDto.getReturnNode())) {
            // 查询上一环节时效
            List<CaseApprovalFlowRelation> priorflows = getPriorCaseApprovalFlow(currentRecord);
            if (priorflows.isEmpty()) {
                throw new BusinessException("未匹配到上一环节审批流配置信息");
            }
            //找出上一步操作记录,插入待审批表
            // 返回上个节点查询上个节点信息
            Example exampleComplete = new Example(CaseApprovalCompleteRecord.class);
            exampleComplete.createCriteria().andEqualTo("caseId", approvalAuditDto.getCaseId()).andGreaterThan("approvalNum", "0").andEqualTo("documentId", currentRecord.get(0).getDocumentId()).andEqualTo("flowRelationId", priorflows.get(0).getId())
                    .andEqualTo("docId", docId);
            //排序查询时间倒序
            exampleComplete.orderBy("approvalTime").desc();
            List<CaseApprovalCompleteRecord> caseApprovalCompleteRecords = caseApprovalCompleteRecordMapper.selectByExample(exampleComplete);
            if (caseApprovalCompleteRecords.isEmpty()) {
                throw new BusinessException("审批完成记录为空");
            }
            //判断审批记录是否存在
            //boolean isExist=checkCaseApprovalWaitRecordIsExist(approvalAuditDto.getCaseId(),currentRecord.get(0).getDocumentId(),approvalAuditDto.getPartyId());
            boolean isExist = checkCaseApprovalWaitRecordIsExistByDocumentId(approvalAuditDto.getCaseId(), docId);
            if (isExist) {
                throw new BusinessException("审批退回失败，待审批记录已存在!");
            }
            CaseApprovalWaitRecord newWaitNode = new CaseApprovalWaitRecord();
            BeanUtils.copyProperties(caseApprovalCompleteRecords.get(0), newWaitNode);
            newWaitNode.setId(StringUtils.uuid());
            newWaitNode.setApprovalStatus(AuditStatusConstant.AUDIT_STATUS_WAIT);
            if (StringUtils.isNotBlank(priorflows.get(0).getApprovalTerm())) {
                Integer term = priorflows.get(0).getApprovalTerm().contains("天") ? new Integer(priorflows.get(0).getApprovalTerm().substring(0, priorflows.get(0).getApprovalTerm().length() - 1)) : new Integer(priorflows.get(0).getApprovalTerm());
                newWaitNode.setApprovalCurrentLimitTime(term);
                newWaitNode.setApprovalCurrentPlanendTime(DateUtils.addDays(new Date(), term));
                newWaitNode.setFlowRelationId(priorflows.get(0).getId());
            }
            newWaitNode.setDocId(docId);
            int newIn = caseApprovalWaitRecordMapper.insert(newWaitNode);
            Boolean f = (newIn == 1 && del == 1 && completeIn == 1);
            if (f) {
                result.put("success", "true");
            } else {
                throw new BusinessException("审批退回数据处理时出现异常");
            }
        }
        return result;
    }

}
